سؤال

I need a simple matrix-algebra or Kronicker product type operation to multiply an array and a vector in R to get to a specific result. Let's say I have the array:

ar<-array(c(rep(1,9),rep(10,9),rep(100,9)),dim=c(3,3,3))

And the vector c(1,2,3). Multiplying both by * multiplies each row on each slide of the array by 1,2, and 3 respectively. However, I need an operation to get to array

ar2<-array(c(rep(1,9),rep(20,9),rep(300,9)),dim=c(3,3,3))

instead. That is, is there a simple operation that would allow me to transform ar to ar2 using the vector I specified above? Thanks!

هل كانت مفيدة؟

المحلول

ar * rep(1:3, each=9) should work...

For an arbitrary sized array and an arbitrary set of multipliers, you know the dimensions of your array and the axis along which you want to perform your elementwise multiplication (in this case, the z axis):

each_arg <- prod(dim(ar)[1:2])
multipliers <- sample(1:10, 3)
ar2 <- ar * rep(multipliers, each=each_arg)

You can also look at the tensorA package

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top