Home > Enterprise >  data.table's equivalent of dplyr's bang bang (!!)
data.table's equivalent of dplyr's bang bang (!!)

Time:11-30

Say I have this DT and ID below:

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

ID <- "b"
DT
#>    ID a  b  c
#> 1:  b 1  7 13
#> 2:  b 2  8 14
#> 3:  b 3  9 15
#> 4:  a 4 10 16
#> 5:  a 5 11 17
#> 6:  c 6 12 18

Is there a {data.table} equivalent of {dplyr}'s:

DT |> dplyr::filter(ID == !!ID)
#>    ID a b  c
#> 1:  b 1 7 13
#> 2:  b 2 8 14
#> 3:  b 3 9 15

Assuming I don't change the variable's name.

CodePudding user response:

Yes, just wrap the variable in as.name():

DT[ID == as.name(ID)]

#    ID a b  c
# 1:  b 1 7 13
# 2:  b 2 8 14
# 3:  b 3 9 15

CodePudding user response:

I like that VitaminB16's answer works in the i= (as well as j=) portions of data.table::[. However, I believe the canonical response to referencing an object from the calling environment is the ..-operator, discussed here: https://rdatatable.gitlab.io/data.table/articles/datatable-intro.html

Unfortunately, it does not work in i=,

DT[ID == ..ID,]
# Error in eval(stub[[3L]], x, enclos) : object '..ID' not found

So must be placed in a .SD. (I believe this works in .SD's i= because it is initially evaluated in the DT's j= ... perhaps convoluted.)

DT[, .SD[ID == ..ID,] ]
#        ID     a     b     c
#    <char> <int> <int> <int>
# 1:      b     1     7    13
# 2:      b     2     8    14
# 3:      b     3     9    15
  • Related