Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Filter a Dataframe based on Category Counts

Tags:

r

filtering

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 up less than 5 times in the whole dataframe?

like image 275
Kyle Brandt Avatar asked Jul 22 '11 22:07

Kyle Brandt


2 Answers

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.

like image 79
joran Avatar answered Sep 22 '22 13:09

joran


Here is another approach (probably cleaner) using plyr.

ddply(dat, .(y), subset, length(x) > 2)
like image 24
Ramnath Avatar answered Sep 24 '22 13:09

Ramnath