Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

r

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?

like image 385
JoeBass Avatar asked Dec 10 '22 19:12

JoeBass


2 Answers

Try:

sweep(Arr,2,Vect,FUN="*")
like image 171
fishtank Avatar answered Jan 05 '23 00:01

fishtank


Cast Vect into an array first, then element multiply:

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)

(also, turns out this is basically what sweep does under the hood...)

like image 23
MichaelChirico Avatar answered Jan 04 '23 23:01

MichaelChirico