Search code examples
rvectorsumsequence

Sequential adding of n elements


I ran into a problem in R where I need to manipulate a vector in R.

Lets say I have a vector of length 12:

vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

I now need to add the elements 1+2, 3+4, 5+6 etc. into a new vector, in the example that would be:

newvector <- c(3, 7, 11, 15, 19, 23) 

I need to do the same for longer sequences, such that it adds the first three, then 4-6, then 7-9 etc.

newvector <- c(6, 15, 24, 33) 

and so on.


Solution

  • Put the vector in a matrix and then use colSums. Here's a function to do that.

    vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
    
    calculate_sum <- function(v, n) {
      colSums(matrix(v, nrow = n))
    }
    
    calculate_sum(vector, 2)
    #[1]  3  7 11 15 19 23
    
    calculate_sum(vector, 3)
    #[1]  6 15 24 33