在dataframe对象中的后续行和

时间:2022-02-13 21:40:45

I would like to do subsequent row summing of a columnvalue and put the result into a new columnvariable without deleting any row by another columnvalue .

我希望对一个columnvalue进行后续的行求和,并将结果放入一个新的columnvariable中,而不通过另一个columnvalue删除任何行。

Below is some R-code and an example that does the trick and hopefully illustrates my question. I was wondering if there is a more elegant way to do since the for loop will be time consuming in my actual object.

下面是一些R-code和一个例子,希望能说明我的问题。我想知道是否有一种更优雅的方法,因为for循环在我的实际对象中会花费时间。

Thanks for any feedback.

谢谢你的任何反馈。

As an example dataframe:

作为一个例子dataframe:

MyDf <- data.frame(ID = c(1,1,1,2,2,2), Y = 1:6)
MyDf$FIRST <- c(1,0,0,1,0,0)
MyDf.2 <- MyDf
MyDf.2$Y2 <- c(1,3,6,4,9,15)

The purpose of this is so that I can write code that calculates Y2 in MyDf.2 above for each ID, separately.

这样做的目的是让我可以编写用MyDf计算Y2的代码。每个ID分别为2。

This is what I came up with and, it does the trick. (Calculating a TEST column in MyDf that has to be equal to Y2 cin MyDf.2)

这就是我想出来的,它很管用。(计算MyDf中必须等于Y2 cin MyDf.2的测试列)

MyDf$TEST <- NA
for(i in 1:length(MyDf$Y)){
MyDf[i,]$TEST <- ifelse(MyDf[i,]$FIRST == 1, MyDf[i,]$Y,MyDf[i,]$Y + MyDf[i-1,]$TEST)
}

MyDf
  ID Y FIRST TEST
1  1 1     1    1
2  1 2     0    3
3  1 3     0    6
4  2 4     1    4
5  2 5     0    9
6  2 6     0   15


MyDf.2
   ID Y FIRST Y2
1  1 1     1  1
2  1 2     0  3
3  1 3     0  6
4  2 4     1  4
5  2 5     0  9
6  2 6     0 15

1 个解决方案

#1


2  

You need ave and cumsum to get the column you want. transform is just to modify your existing data.frame.

你需要ave和cumsum才能得到你想要的那一列。转换只是修改现有的data.frame。

> MyDf <- transform(MyDf, TEST=ave(Y, ID, FUN=cumsum))
  ID Y FIRST TEST
1  1 1     1    1
2  1 2     0    3
3  1 3     0    6
4  2 4     1    4
5  2 5     0    9
6  2 6     0   15

#1


2  

You need ave and cumsum to get the column you want. transform is just to modify your existing data.frame.

你需要ave和cumsum才能得到你想要的那一列。转换只是修改现有的data.frame。

> MyDf <- transform(MyDf, TEST=ave(Y, ID, FUN=cumsum))
  ID Y FIRST TEST
1  1 1     1    1
2  1 2     0    3
3  1 3     0    6
4  2 4     1    4
5  2 5     0    9
6  2 6     0   15

相关文章