简体   繁体   English

R对于每个第三维,通过向量乘以3D阵列的第二维

[英]R Multiply second dimension of 3D Array by a Vector for each of the 3rd dimension

When trying to multiply the first dimension of an array by each index of a vector by the second dimension, my array is converted to a matrix and things get squirrelly. 当尝试将数组的第一个维度乘以向量的每个索引乘以第二个维度时,我的数组将转换为矩阵,并且事情变得松散。 I can only do the proper multiplication long-hand. 我只能长时间做适当的乘法。

What a mouth full... 多么满口......

It's easier to explain with code... 使用代码更容易解​​释......

Arr <- array(runif(10*5*3), dim = c(10,5,3))
dim(Arr)
Vect <- c(1:5)

Arr[,1,1] <- Arr[,1,1]*Vect[1]
Arr[,1,2] <- Arr[,1,2]*Vect[1]
Arr[,1,3] <- Arr[,1,3]*Vect[1]

Arr[,2,1] <- Arr[,2,1]*Vect[2]
Arr[,2,2] <- Arr[,2,2]*Vect[2]
Arr[,2,3] <- Arr[,2,3]*Vect[2]

Arr[,3,1] <- Arr[,3,1]*Vect[3]
Arr[,3,2] <- Arr[,3,2]*Vect[3]
Arr[,3,3] <- Arr[,3,3]*Vect[3]

Arr[,4,1] <- Arr[,4,1]*Vect[4]
Arr[,4,2] <- Arr[,4,2]*Vect[4]
Arr[,4,3] <- Arr[,4,3]*Vect[4]

Arr[,5,1] <- Arr[,5,1]*Vect[5]
Arr[,5,2] <- Arr[,5,2]*Vect[5]
Arr[,5,3] <- Arr[,5,3]*Vect[5]

How do I clean this up to be one command? 如何将其清理为一个命令?

Cast Vect into an array first, then element multiply: 首先将Vect转换为数组,然后将元素乘以:

varr <- aperm(array(Vect, dim = c(5L, 10L, 3L)), perm = c(2L, 1L, 3L))

Arr <- varr * Arr

(of course we don't need to store varr if you want this in one command) (当然,如果你想在一个命令中使用它,我们不需要存储varr

(also, turns out this is basically what sweep does under the hood...) (另外,事实证明这基本上是sweep引擎盖下的......)

尝试:

sweep(Arr,2,Vect,FUN="*")

The aaply() function from the plyr package does exactly what you're looking for. plyr包中的aaply()函数正是您正在寻找的。 It can operate on arrays of any dimension and split them however you like. 它可以在任何维度的数组上运行,并根据需要拆分它们。 In this case you're splitting by rows so: 在这种情况下,您按行拆分:

library(plyr)
Arr2 <- aaply(Arr, 1, function(x,y){x*y}, Vect)

We can also replicate the 'Vect' and multiply with 'Arr'. 我们也可以复制'Vect'并乘以'Arr'。 The col is a convenient function that gives the numeric index of columns. col是一个方便的函数,它提供列的数字索引。

res1 <- Arr * Vect[col(Arr[,,1])]

Or we explicitly do the rep 或者我们明确地做rep

res2 <- Arr* rep(Vect, each=dim(Arr)[1])
identical(res1, res2)
#[1] TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM