I'm trying to wrap my head around quasiquotation so that I could use it together with a data.table
call. Here is an example:
library(data.table)
library(rlang)
dt <- data.table(col1 = 1:10, col2 = 11:20)
dt[, col1]
If I wanted to wrap this into function, how would I do this? I tried:
foo <- function(dt, col) {
col <- quo(col)
expr(dt[, !!col1])
}
foo(dt, col1)
But get Error in enexpr(expr) : object 'col1' not found
. I assume I'm missing some steps as data.table
evaluates this differently than dplyr
.
You want to capture the column name as a symbol with
rather than
quo()
and then use(not
col1
which doesn't exist there) but that will just return an expression. If you want to evaluated it, you'd needBut really the quasinotation stuff works best in the tidyverse and not with data.table functions natively. The "data.table" way might be more like something in this existing question: Pass column name in data.table using variable. data.table very much prefers strings to symbols.