Chris
Chris

Reputation: 1237

Subset data.table by condition but retain all rows belonging to group

I have data that looks like this:

require("data.table")
dt1 <- data.table(
  code=c("A001", "A001","A001","A002","A002","A002","A002","A003","A003"),
  value=c(40,38,55,10,12,16,18,77,87))

I would like to subset it so any group (code) that contains a value over or under a given number is retained. For example, if I wanted any group that contained a value over 50 then the result would look like this:

dt2 <- data.table(
  code=c("A001", "A001","A001","A003","A003"),
  value=c(40,38,55,77,87))

Upvotes: 3

Views: 97

Answers (1)

akrun
akrun

Reputation: 887118

We create a condition with any after grouping by 'code' to subset the rows

dt1[, if(any(value > 50)) .SD,  code]

Or without the if condition

dt1[,  .SD[any(value > 50)],  code]

Or get the row indices (.I) and subset based on that

dt1[dt1[,  .I[any(value > 50)],  code]$V1]

Upvotes: 7

Related Questions