Keeping only the x largest groups with data.table

Viewed 102

I have recently started using the data.table package in R, but I recently stumbled into an issue that I do not know how to tackle with data.table.

Sample data:

set.seed(1)
library(data.table)
dt = data.table(group=c("A","A","A","B","B","B","C","C"),value = runif(8))

I can add a group count with the statement

dt[,groupcount := .N ,group]

but now I only want to keep the x groups with the largest value for groupcount. Let's assume x=1 for the example.

I tried chaining as follows:

dt[,groupcount := .N ,group][groupcount %in% head(sort(unique(groupcount),decreasing=TRUE),1)]

But since group A and B both have three elements, they both remain in the data.table. I only want the x largest groups where x=1, so I only want one of the groups (A or B) to remain. I assume this can be done in a single line with data.table. Is this true, and if yes, how?


To clarify: x is an arbitrarily chosen number here. The function should also work with x=3, where it would return the 3 largest groups.

3 Answers
Related