简体   繁体   English

如何将 R 中数据框列表中同一列的行相乘

[英]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:我有一个数据框列表,我在列表中的每个 dataframe 中创建了一个额外的列(列表中的数据框没有相同数量的观察值)并想用以下公式填充每个 dataframe 中的额外列:

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.所以我正在做的是在 xD 的第二行乘以 xC 的第一行和第二行,在 xD 的第三行乘以 xC 的第一行和第三行,依此类推。

Is there a way of doing this.有没有办法做到这一点。

Thanks谢谢

Here is how to achieve what you need using slider and Reduce .以下是如何使用sliderReduce实现您的需求。

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)reprex package (v2.0.1) 创建于 2022-04-05

Slider allows you to capture windows of your data. Slider允许您捕获 windows 的数据。

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. Reduce允许您在向量的所有成员之间应用 function。 For example, if the vector is c(1, 2, 3) and the function is * , then it results in 1*2*3 = 6.例如,如果向量是c(1, 2, 3)并且 function 是* ,那么它的结果是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.结合sliderReduce ,你可以实现你所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM