Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Created August 31, 2024 06:14
Show Gist options
  • Save nilforooshan/1df7335e02b9b28fa7dc2bf77aa78bf1 to your computer and use it in GitHub Desktop.
Save nilforooshan/1df7335e02b9b28fa7dc2bf77aa78bf1 to your computer and use it in GitHub Desktop.
R: Various ways to select multiple columns in data.table

Various ways of selecting multiple columns in a data.table

An example data.table:

DT = data.table(
    ID = c("b","b","b","a","a","c"),
    a = 1:6,
    b = 7:12,
    c = 13:18
)
keep_cols <- c("a", "c")

All the following commands

DT[,.(a, c)]
DT[,c("a", "c")]
DT[,c(2,4)]
DT[, .SD, .SDcols = c(2,4)]
DT[, .SD, .SDcols = keep_cols]
DT[,..keep_cols]

result in

       a     c
   <int> <int>
1:     1    13
2:     2    14
3:     3    15
4:     4    16
5:     5    17
6:     6    18

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment