Search code examples
rdplyrrollapplysumproduct

Is there an R function for sumproduct the last 4 rows in a dataframe?


I need a function like sumproduct (excel) but only for the last 4 rows.

Im using dplyr and i tried sumproduct with rollapply but i can only sum the last 4 rows of one column while i need multiply 2 columns by each row and then sum it by the last 4 rows like sumproduct from excel.

x1 <- c(84,105,79,140,108,79,112,118,114,92)
x2 <- c(138,110,84,45,128,99,100,124,121,115)
df <- data.frame(x1,x2)

I expect a result like this:

x3 <- c(NA,NA,NA,36078,38310,34581,39145,47477,47447,50206)

Solution

  • Multiply the columns together and then compute the rolling sum:

    library(zoo)
    
    with(df, rollsumr(x1 * x2, 4, fill = NA))
    ## [1]    NA    NA    NA 36078 38310 34581 39145 47477 47447 50206
    

    This could also be expressed using a dplyr pipeline:

    library(dplyr)
    library(zoo)
    
    df %>% 
      { x1 * x2 } %>%
      rollsumr(4, fill = NA)
    

    or to create a 3 column data frame with the rolling sum as the third column:

    df %>%
      mutate(roll = rollsumr(x1 * x2, 4, fill = NA))