user1165199
user1165199

Reputation: 6649

Add each element of vector to another vector

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

Answers (4)

lmo
lmo

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

akrun
akrun

Reputation: 887118

We can use outer with FUN as +

c(outer(x, y, `+`))
#[1] 3 3 6 4 4 7

Upvotes: 9

count
count

Reputation: 1338

Or you can try:

as.vector(sapply(y,function(i) (i+x)))

Upvotes: 0

Cath
Cath

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

Related Questions