Subset a list - a plyr way?

蹲街弑〆低调 提交于 2019-12-03 16:57:54

At least in this situation this gives the same result

library(plyr)
dd5 <- ddply(dd,.(group),function(x) x[max(x$mass)<45,])

all(dd4==dd5)
[1] TRUE
mnel

Here is a data.table solution for coding elegance

library(data.table)
DT <- data.table(dd)

DT[,if(max(mass) < 45){.SD},by=group]
    group     mass
 1:     a 28.80426
 2:     a 31.31232
 3:     a 29.47599
 4:     a 30.35425
 5:     a 29.92833
 6:     c 40.11349
 7:     c 40.17431
 8:     c 39.94652
 9:     c 39.57524
10:     c 40.20791

Perhaps slightly more convoluted

new <- (DT[,index := max(mass) < 45,by=group][force(index)])[,index:=NULL]

I realize that you have specifically asked for a plyr solution, but I thought I would also share an alternative way to do this in base R that does not involve your multi-step approach:

dd[as.logical(ave(dd$mass, dd$group, FUN = function(x) max(x) < 45)), ]

The ave function is usually handy when dealing with groups in R. Here, I've created a logical vector, and subsetted based on the indices of the "TRUE" values.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!