如何解决如何将array12D添加到array23D?
我有2个数组,它们共享2个维度,但是一个数组有一个额外的维度:
allpets <- array(data = 1:9,dim= c(3,3))
dimnames(allpets)[[2]]<-c("age","height","weight")
species<-array(data = 27:54,dim = c(3,3,3))
dimnames(species)[[2]]<-c("age","weight")
dimnames(species)[[3]]<-c("dog","cat","fish")
allpets
age height weight
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
species,dog
age height weight
[1,] 27 30 33
[2,] 28 31 34
[3,] 29 32 35,cat
age height weight
[1,] 36 39 42
[2,] 37 40 43
[3,] 38 41 44,fish
age height weight
[1,] 45 48 51
[2,] 46 49 52
[3,] 47 50 53
我想将第一个数组allpets添加到该数组的每个物种的匹配列中,称为物种,所以结果是:
,] 28 34 40
[2,] 30 36 42
[3,] 32 38 44,] 37 43 49
[2,] 39 45 51
[3,] 41 47 53,] 46 52 58
[2,] 48 54 60
[3,] 50 56 62
我尝试使用Apply,但是似乎无法为正确的部分编制索引以使其正常工作?
sumpet <- function(x) {
x + allpets
}
apply(species,c(2,3),sumpet)
我觉得这相对简单,但是我没有使用正确的词来寻找解决方案。从概念上讲,petpet是某些响应的基线,我正在尝试将此基线添加到每个物种级别的响应中。
谢谢!
解决方法
您可以使用sweep()
:
sweep(species,1:2,allpets,FUN = "+")
#>,dog
#>
#> age height weight
#> [1,] 28 34 40
#> [2,] 30 36 42
#> [3,] 32 38 44
#>
#>,cat
#>
#> age height weight
#> [1,] 37 43 49
#> [2,] 39 45 51
#> [3,] 41 47 53
#>
#>,fish
#>
#> age height weight
#> [1,] 46 52 58
#> [2,] 48 54 60
#> [3,] 50 56 62
使用apply
的另一种方法。由于apply(...)
转换为矩阵,因此需要更多的费用。
array(apply(species,3L,"+",allpets),dim(species),dimnames(species))
,
您可以将lapply
嵌入simplify2array
中。
simplify2array(setNames(lapply(seq(dim(species)[3]),function(x) species[,x] + allpets),dimnames(species)[[3]]))
#,dog
#
# age height weight
# [1,] 28 34 40
# [2,] 30 36 42
# [3,] 32 38 44
#
#,cat
#
# age height weight
# [1,] 37 43 49
# [2,] 39 45 51
# [3,] 41 47 53
#
#,fish
#
# age height weight
# [1,] 46 52 58
# [2,] 48 54 60
# [3,] 50 56 62
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。