I am trying to subset rows of a data.table programatically inside an R function. The following works as expected:
dt <- data.table(id = 1:5, variable = c("test","data","data", "is", "fun"))
dt[variable == "data"]
id variable
1: 2 data
2: 3 data
If I define the function:
dtSubset <- function(df, col, str) {
df[col == str]
}
dtSubset(df, "variable", "data")
I get a 0-row table.
The following works:
dtSubset <- function(df, str) {
dt[variable == str]
}
dtSubset(df, "data")
so the issue lies with selecting the column inside the function.
I tried combinations of eval
, substitute
, quote
and deparse
, quoting and unquoting the column name to be passed in, each to no avail. I also tried out subset
but ran into the same issues.
The vignettes describe how to do this in j
but not in i
. Not sure if I've missed something obvious or whether I'm just thinking wrong, but how should I be going about doing this?