且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R data.table:为所有行中有条件的行子集添加新列

更新时间:2023-12-01 11:43:58

您应该颠倒定义 groupmean 。将其计算为所有行的组平均值,然后替换 condition == TRUE 之后的行。

You should reverse the sequence of how you define groupmean. Compute it as the group average for all rows, and substitute the rows where condition == TRUE afterwards.

DT[, groupmean:=mean(numbers), by=group]
DT[condition==TRUE, groupmean:=mean(numbers), by='group,condition']

我希望对您有所帮助