[英]Add each element of vector to another vector
I have 2 vectors 我有2个向量
x <- c(2,2,5)
y <- c(1,2)
I want to add each element of the vectors together to get 我想将向量的每个元素组合在一起得到
[1] 3 3 6 4 4 7
How can I do this? 我怎样才能做到这一点?
We can use outer
with FUN
as +
我们可以使用FUN
outer
作为+
c(outer(x, y, `+`))
#[1] 3 3 6 4 4 7
You can try creating each pair of x/y elements with expand.grid
and then computing the row sums: 您可以尝试使用expand.grid
创建每对x / y元素,然后计算行总和:
rowSums(expand.grid(x, y))
# [1] 3 3 6 4 4 7
You can also use variations of rep
with +
: 您还可以使用的变化rep
与+
:
rep(x, length(y)) + rep(y, each=length(x))
[1] 3 3 6 4 4 7
The second argument to +
uses the each argument to rep
which repeats each element of y corresponding to the length of x. +
的第二个参数使用rep
的每个参数重复y的每个元素,对应于x的长度。
或者您可以尝试:
as.vector(sapply(y,function(i) (i+x)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.