如何将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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...