user9798936
user9798936

Reputation:

Sequential sum of a list of vectors

Let x, y, and z be vectors with an equal length. Assume that I would like to sum them sequentially, i.e., x +y, then x+y+z. Suppose I have a list of 20 vectors. Is there an easy way to do this?

 x <- c(1,2,3,45)
 y <- c(2,31,31,4)
 z <- c(3,4,54,6)

Here is my expected output:

>  s <- x+y
> s
[1]  3 33 34 49

>  z+s
[1]  6 37 88 55

Upvotes: 3

Views: 190

Answers (1)

Sotos
Sotos

Reputation: 51582

Here is a possible route. Put your vectors into a list and fix their length to be the same. You can achieve this by padding NAs to all vectors to reach the same vector length as the maximum. The you can use Reduce with the argument accumulate = TRUE to apply the function sequentially, i.e.

l1 <- list(x, y, z)
l1 <- lapply(l1, `length<-`, max(lengths(l1)))

Reduce(`+`, l1, accumulate = TRUE)
#[[1]]
#[1]  1  2  3 45 34

#[[2]]
#[1]  3 33 34 49 NA

#[[3]]
#[1]  6 37 88 55 NA

NOTE: If your vectors are all the same length, then you can just put them in a list and go directly to Reduce, i.e. Reduce(`+`, list(x, y, z), accumulate = TRUE)

Upvotes: 1

Related Questions