开发者

How To Filter a Dataframe based on Category Counts

开发者 https://www.devze.com 2023-03-22 03:40 出处:网络
How do I subset a dataframe so that only rows that contain columns that have a value that shows up a certain amount of times in other rows are included.

How do I subset a dataframe so that only rows that contain columns that have a value that shows up a certain amount of times in other rows are included.

For example, if I have a column labeled Food, how would I filter out all rows that have a food that shows u开发者_C百科p less than 5 times in the whole dataframe?


Here's a quick example:

dat <- data.frame(x=runif(50),y=sample(letters,50,replace = TRUE))
dat[dat$y %in% names(table(dat$y))[table(dat$y) > 2],]

That selects all rows that contain a letter that appears more than twice.


Here is another approach (probably cleaner) using plyr.

ddply(dat, .(y), subset, length(x) > 2)


I'm a fan of ave for problems like this. Using the example data from @joran's answer:

set.seed(21)
dat <- data.frame(x=runif(50), y=sample(letters,50,replace=TRUE))
foo <- dat[dat$y %in% names(table(dat$y))[table(dat$y) > 2],]
bar <- subset(dat, ave(rep(1,nrow(dat)), dat$y, FUN=sum) > 2)
identical(foo,bar)
# [1] TRUE
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号