0

I have this dataset : dataset

I would like to get a new vector (rendimenti.2) that contains the sum of 24 observations at a time. The dataset contains 35232 observations, so the new vector will have 35232: 24 = 1468 observations, how to do in R?

  • 2
    Simple approach: add a grouping column `df$group = (1:nrow(df) - 1) %/% 24` and then pick your favorite answer from the FAQ on [How to sum data by group](https://stackoverflow.com/q/1660124/903061). There may be a smarter way to create the groups, depending on the meaning of your data. – Gregor Thomas Oct 16 '19 at 14:58

1 Answers1

0

It's two parts: how to divide your data into groups of 24, and how to calculate the sums by groups. Here is one way:

tapply(dataset$rendimenti, trunc(0:35231/24), sum)

aggregate is another answer to the second part of the question. And of course, sapply and dplyr::summarise can do it as well.

For the first sub-question, you can use %/% as in Gregor's comment to the OP, or rep (say, rep(1:(35232/24), length.out=35232, each=24)).

lebatsnok
  • 6,329
  • 2
  • 21
  • 22