Search code examples
arraysrmultiplication

R Multiplying each element of an array by a different number


I am trying to multiply each element of an array by an integer (along the first dimension). The tricky thing is that this integer will change for each element.

An example :

test <- array(dim = c(3,5,7))
test[1,,] <- 1
test[2,,] <- 10
test[3,,] <- 100

vec <- c(1,2,3)

The result I want is an array with the same dimension (3,5,7) and along the first dimension :

test[1,,] * vec[1]
test[2,,] * vec[2]
test[3,,] * vec[3]

This means

Result <- array(dim = c(3,5,7))
Result[1,,] <- 1
Result[1,,] <- 20
Result[1,,] <- 300

I think I am quite close with different functions like outer or apply but I think there is an easier way, as I have a lot of data to treat. For now, I found the outer function, and I should select something like the diagonal of the result.

Can someone help ?


Solution

  • slice.index might be helpful here

    Result <- test * vec[slice.index(test, 1)]