cdeterman
cdeterman

Reputation: 19960

R - Concisely add vector to each vector element

Let's say I have a simple vector

v <- 1:5

I can add the vector to each element within the vector with the following code to generate the resulting matrix.

matrix(rep(v, 5), nrow=5, byrow=T) + matrix(rep(v, 5), nrow=5)

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

But this seems verbose and inefficient. Is there a more concise way to accomplish this? Perhaps some linear algebra concept that is evading me?

Upvotes: 3

Views: 78

Answers (2)

Saksham
Saksham

Reputation: 9380

Posting this answer not for up votes but to highlight Franks comment. You can use

sapply(v,"+",v)

Upvotes: 0

Rorschach
Rorschach

Reputation: 32426

outer should do what you want

outer(v, v, `+`)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    3    4    5    6
# [2,]    3    4    5    6    7
# [3,]    4    5    6    7    8
# [4,]    5    6    7    8    9
# [5,]    6    7    8    9   10

Upvotes: 5

Related Questions