filter a data.table in r

To subset a data.table in R, you can use the i argument. The syntax for subsetting is:

main.r
DT[i, j, by]
13 chars
2 lines

where DT is the data.table, i is the logical condition to filter rows, j is the columns to select, and by is the grouping variable.

Here's an example of filtering a data.table using the i argument:

main.r
library(data.table)
DT <- data.table(x = c("a", "b", "c", "d", "e"),
                 y = 1:5,
                 z = c(TRUE, FALSE, TRUE, FALSE, TRUE))

# filter rows where z is TRUE
DT[z == TRUE]
196 chars
8 lines

Output:

main.r
   x y    z
1: a 1 TRUE
2: c 3 TRUE
3: e 5 TRUE
48 chars
5 lines

In this example, we filtered the rows of DT where z == TRUE using the i argument.

related categories

gistlibby LogSnag