Search code examples
rdataframesumrowscalculated-columns

Sum each four rows in a column


I'm a beginner in R and I really need your help. I'm trying to get a new dataframe that stores the sum of each five rows in my columns.

For example, I have a dataframe (delta) with two columns (A,B)

A B   
2 3   
1 2  
3 2  
4 5  
3 7  
5 6  
2 5  

and the output I'm looking for is

AA BB  
13 19  
16 22  
17 25  

where

13 = row1+row2+row3+row4+row5
16 = row2+row3+row4+row5+row6 

and so on ...

I have no idea where to start. Thanks a lot for your help guys.


Solution

  • The subject refers to 4 rows but the example in the question refers to 5. We have used 5 below but if you intended 4 just replace 5 with 4 in the code.

    1) rollsum Using the reproducible input in the Note at the end use rollsum . Omit the as.data.frame if a matrix is ok as output.

    library(zoo)
    
    as.data.frame(rollsum(DF, 5))
    ##    A  B
    ## 1 13 19
    ## 2 16 22
    ## 3 17 25
    

    2) filter filter in base R works too. Note that if you have dplyr loaded it clobbers filter so in that case use stats::filter in place of filter to ensure you get the correct version.

    setNames(as.data.frame(na.omit(filter(DF, rep(1, 5)))), names(DF))
    ##    A  B
    ## 1 13 19
    ## 2 16 22
    ## 3 17 25
    

    Note

    Lines <- "
    A B
    2 3
    1 2
    3 2
    4 5
    3 7
    5 6
    2 5"
    DF <- read.table(text = Lines, header = TRUE)