Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Concisely add vector to each vector element

Tags:

r

vector

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?

like image 333
cdeterman Avatar asked Dec 20 '25 20:12

cdeterman


1 Answers

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
like image 64
Rorschach Avatar answered Dec 23 '25 10:12

Rorschach