T.Y. Lin
T.Y. Lin

Reputation: 11

R. Multiply a different scalar to every element of a list and sum over the elements

Suppose a list object and a vector:

lst <- list(a = matrix(1:9, 3), b = matrix(2:10, 3))
vec <- c(2, 3)

And I want to get the result like

2 * a + 3 * b

I solve this by

matrix(apply(mapply("*", lst, vec), 1, sum), 3, 3)

But this looks a little cumbersome.

Is there an efficient way to get same result?

Upvotes: 1

Views: 348

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

Not sure if it's any more efficient, but here's an idea that's a little cleaner. You can use Map() for the multiplication and Reduce() to do the summing.

Reduce("+", Map("*", lst, vec))
#      [,1] [,2] [,3]
# [1,]    8   23   38
# [2,]   13   28   43
# [3,]   18   33   48

Also, in your code, you could replace the apply() call with rowSums(). That would probably improve efficiency in what you've done.

Upvotes: 1

akrun
akrun

Reputation: 887048

Another option is loop through the sequence of the list and then multiply

Reduce(`+`,lapply(seq_along(lst), function(i) lst[[i]]*vec[i]))

For the list and vector of two elements

lst[[1]]*vec[1] + lst[[2]] * vec[2]

Upvotes: 0

Related Questions