Add each element of the vector to a different 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?

+4
source share
4 answers

We can use outerwith FUNas+

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

You can try to create each pair of x / y elements with expand.grid, and then calculate the sums of the lines:

rowSums(expand.grid(x, y))
# [1] 3 3 6 4 4 7
+3
source

rep +:

rep(x, length(y)) + rep(y, each=length(x))
[1] 3 3 6 4 4 7

+ rep, y, x.

+1

:

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

Source: https://habr.com/ru/post/1671237/


All Articles