Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add each element of vector to another vector

Tags:

r

add

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?

like image 284
user1165199 Avatar asked Mar 02 '17 10:03

user1165199


2 Answers

We can use outer with FUN as +

c(outer(x, y, `+`))
#[1] 3 3 6 4 4 7
like image 110
akrun Avatar answered Sep 28 '22 09:09

akrun


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
like image 24
Cath Avatar answered Sep 28 '22 10:09

Cath