Octobanana
Octobanana

Reputation: 11

How to sum elements by intervals?

I am wondering how I can use dplyr (or other methods) to sum intervals of elements of a vector?

Lets say I have the vector: v = rep(2,800). I want to get a new vector with the sums of intervals of 16 elements, having the content like this:

Vsum <- c(sum(v[1:16]), sum(v[17:32]), ..., sum(v[785:800]) )
length(Vsum)
[1] 50

NB! What I have tried myself:

sixteen <- seq(1,800,16)
sixteen_end <- sixteen + 15
sum(test[seksten:seksten_slutt])
[1] 32

But it only sum the first interval (1:16) and not for the rest of vector v.

Upvotes: 0

Views: 474

Answers (1)

GKi
GKi

Reputation: 39647

You can use matrix with colSums:

colSums(matrix(v, 16))

Upvotes: 2

Related Questions