Laura
Laura

Reputation: 13

New vector as sum of elements according to rule

I need a rule that creates a new vector such that the first element = the first element of vector 1, second element = the sum of second element of vector 1 and first element of vector 2, third element = the sum of third element of vector 1, second element of vector 2 and first element of vector 3, ..., the last element is the last element of the last vector.

for example, with two vectors (v1, v2),

v1 <- c(1, 2, 3)

v2 <- c(4, 5, 6)

new.vector <- c(1, 6, 8, 6)

Much appreciate all suggestions!

Upvotes: 0

Views: 93

Answers (2)

mt1022
mt1022

Reputation: 17309

What about adding a leading 0 and a trailing 0 to v1 and v2, respectively:

c(v1, 0) + c(0, v2)

To make it a function:

f <- function(v1, v2) c(v1, 0) + c(0, v2)

Upvotes: 2

d.b
d.b

Reputation: 32558

c(v1[1], v2+c(v1[-1],0))
#[1] 1 6 8 6

Put in a function if you want

foo = function(x, y){
    return(c(x[1], y+c(x[-1],0)))
}
foo(v1, v2)
#[1] 1 6 8 6

Upvotes: 1

Related Questions