[英]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?
也许是一些躲避我的线性代数概念?
outer
should do what you want outer
应该做你想要的
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
Posting this answer not for up votes but to highlight Franks comment. 发布这个答案不是为了投票,而是为了突出法兰克斯的评论。 You can use
您可以使用
sapply(v,"+",v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.