'How to multiply rows from same column in a list of dataframes in R

I have a list of data frames, I created an extra column in each dataframe in the list (dataframes in the list doesn´t have same number of observations) and would like to fill the extra column in each dataframe with the following formula:

one of the dataframes in the list (all dataframes have same variables but different number of observations)

   xA  xB  xC  xD   
   2   1   1   NA
   2   1   2   NA
   3   1   3   NA
   3   4   4   NA 
   5   5   5   NA

formula required

  xA  xB  xC  xD   
  2   1   1   2   ======>(1+xC1)=(1+1)=2
  2   1   2   6   ======>(1+xC1)*(1+xC2)=(1+1)*(1+2)=6
  3   1   3   24  ======>(1+xC1)*(1+xC2)*(1+xC3)=(1+1)*(1+2)*(1+3)=24
  3   4   4   120 ======>(1+xC1)*(1+xC2)*(1+xC3)*(1+xC4)=(1+1)*(1+2)*(1+3)*(1+4)=120
  5   5   5   720 ======>(1+xC1)*(1+xC2)*(1+xC3)*(1+xC4)*(1+xC5)=(1+1)*(1+2)*(1+3)*(1+4)*(1+5)=720

so what I am doing is multipling in the second row of xD the first and second row of xC, in the third row of xD the first second and third row of xC and so on.

Is there a way of doing this.

Thanks



Solution 1:[1]

Here is how to achieve what you need using slider and Reduce.

library(slider)

df <- data.frame(
  xA = c(2, 2, 3, 3,  5),
  xB = c(1, 1, 1, 4, 5),
  xC = 1:5,
  xD = rep(NA, 5)
)

df$xD <- unlist(slide(df$xC, ~Reduce(.x + 1, f = "*"), .before = Inf))

df
#>   xA xB xC  xD
#> 1  2  1  1   2
#> 2  2  1  2   6
#> 3  3  1  3  24
#> 4  3  4  4 120
#> 5  5  5  5 720

Created on 2022-04-05 by the reprex package (v2.0.1)

Slider allows you to capture windows of your data.

slide(1:5,.f = ~.x, .before = Inf)
[1]]
[1] 1

[[2]]
[1] 1 2

[[3]]
[1] 1 2 3

[[4]]
[1] 1 2 3 4

[[5]]
[1] 1 2 3 4 5

Reduce lets you apply a function between all members of a vector. For example, if the vector is c(1, 2, 3) and the function is *, then it results in 1*2*3 = 6.

Reduce(f = "*", 1:5) # aka 1*2*3*4*5 = 120
[1] 120

Combining slider and Reduce, you can achieve what you need.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub.Novotny