如何将二维数组array1添加到三维数组array2中?

3

我有两个数组共享两个维度,但其中一个具有额外的维度:

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
谢谢,这个方法有效!你可以将它添加为答案。 - BirdNerd
2个回答

4
你可以使用 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))

这个虽然会抛出一个警告,但对我的数据集来说并不是问题。谢谢! - BirdNerd
你好,纯属好奇,你使用的是哪个版本的R语言?我在4.0.2版本中的sweepapply函数中没有看到任何警告。最后,检查解决方案总是一个好习惯,但你可以等待更多答案或选择其他答案。 - Cole
我使用的是 R 3.4.4 版本,警告是关于 sweep 版本的。 - BirdNerd

1
你可以在 simplify2array 中嵌入一个 lapply
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接