Reputation: 6649
I have 2 vectors
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?
Upvotes: 7
Views: 1415
Reputation: 38500
You can also use variations of rep
with +
:
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.
Upvotes: 1
Reputation: 887118
We can use outer
with FUN
as +
c(outer(x, y, `+`))
#[1] 3 3 6 4 4 7
Upvotes: 9
Reputation: 24074
You can try creating each pair of x/y elements with expand.grid
and then computing the row sums:
rowSums(expand.grid(x, y))
# [1] 3 3 6 4 4 7
Upvotes: 4