我有两个数组共享两个维度,但其中一个具有额外的维度:
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","height","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添加到名为species数组中每个物种的匹配列,以便结果如下:
, , 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,但似乎无法索引正确的部分使其正常工作?
sumpet <- function(x) {
x + allpets
}
apply(species,c(2,3),sumpet)
我有一种感觉这个问题相对简单,但是我用的搜索词不正确。从概念上讲,“allpets”是某个响应的基准,我正在尝试将该基准添加到每个物种级别的响应中。
先行感谢!
species + array(allpets, dim = dim(species))
,尽管这会涉及创建一个全新的数组。 - user20650