且构网

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

如何创建一个列,包括R中另一列的最大值?

更新时间:2022-12-10 14:15:10

dat$MaxAct <- with(dat, ave(ActNo, HHID, PERID, FUN=max) )

涉及单个向量和分组的问题,其中您希望结果的长度等于行计数, ave 是您的选择的功能。对于更复杂的问题,可能需要 lapply(split(dat,fac),FUN)方法或使用 do.call(rbind,by ...))

For problems involving single vectors and grouping where you want the length of the result to equal the row count, ave is your function of choice. For more complicated problems, the lapply(split(dat, fac), FUN) approach may be needed or use do.call(rbind, by( ...))

如果您缺少值:

dat$MaxAct <- with(dat, ave(ActNo, HHID, PERID, FUN=function(x) max(x, na.rm=TRUE) )  )