R - Concisely add vector to each vector element

时间:2015-07-28 16:56:19

标签: 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?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

发布此答案不是为了投票,而是为了突出法兰克斯的评论。你可以使用

sapply(v,"+",v)