'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 1:[1]

How about

test*replicate(7, replicate(5, vec))

Solution 2:[2]

What's wrong with using apply like this?

sapply(1:length(vec), function(i) test[i,,]<<- test[i,,]*vec[i])

Solution 3:[3]

In this case you can just do

Result <- test*vec

Note that this will only work if the dimension that is being split and multiplied is the first one.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Tyers
Solution 2 bala83
Solution 3 Carlos Llosa