Add vector coefficients to matrix

I would like to add every coefficient of the vector to every other column of the matrix. For example, if I have a vector and a matrix:

x <- c(1,2,3)
M <- matrix(c(5,6,7), nrow = 3, ncol = 3)

      

I would like in my new matrix M1

1 + 5 in the first column 2 + 6 in the second and 3 + 7 in the last.

Is there any function in R that does this task?

+3


source to share


1 answer


try this:

M + rep(x, each = nrow(M))

      

or that:

apply(M, 1, `+`, x)

      

result:



     [,1] [,2] [,3]
[1,]    6    7    8
[2,]    7    8    9
[3,]    8    9   10

      

EDIT: akrun commented on two other great solutions:

M + x[col(M)]

      

and

sweep(M, 2, x, "+")

      

+2


source







All Articles