subsetting in data.table

exl picture exl · Mar 30, 2011 · Viewed 55k times · Source

I am trying to subset a data.table ( from the package data.table ) in R (not a data.frame). I have a 4 digit year as a key. I would like to subset by taking a series of years. For example, I want to pull all the records that are from 1999, 2000, 2001.

I have tried passing in my DT[J(year)] binary search syntax the following:

1999,2000,2001
c(1999,2000,2001)
1999, 2000, 2001

but none of these seem to work. Anyone know how to do a subset where the years you want to select are not just 1 but multiple years?

Answer

Richie Cotton picture Richie Cotton · Mar 30, 2011

What works for data.frames works for data.tables.

subset(DT, year %in% 1999:2001)