I'm creating a function for my co-workers to easily analyze some pre-specified datasets. I would like for them to be able to pass "i" arguments to select rows. To make it more robust, I would like to be able pass this argument with or without quotes.
Here is an example that works with quotes …
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
where <- parse(text = paste0(list(...)))
my.dt <- my.dt[eval(where), ]
return(my.dt)
}
tmp <- test.function(x, 'x==3 | sex=="F"')
head(tmp)
If I remove the quotes, it fails saying "object 'sex' not found"…
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
where <- parse(text = paste0(list(...)))
my.dt <- my.dt[eval(where), ]
return(my.dt)
}
tmp <- test.function(x, x==3 | sex=="F")
head(tmp)
In addition to the above, I have many failed attempts using quote, substitution and rlang: like this failed example …
x <- data.table(x = c(1,1,1,2,2,2,3,3,3),
sex = c("M", "M", "F","M", "F","M", "F","M", "F"))
test.function <- function(my.dt, ...){
where <- rlang::quos(...)
my.dt <- my.dt[!!where, ]
return(my.dt)
}
tmp <- test.function(x, 'x==3 | sex=="F"')
head(tmp, 10)
In addition to any ideas for solutions, I would be grateful if someone could point me toward an simpleton's online resource for understanding symbols/expressions/quotes/etc. As I dug into this problem I realized that I have some serious gaps in my understanding of how R works.
BTW, I've already read through the following, but neither was able to help me: Passing function argument to data.table i and Passing multiple arguments to data.table inside a function .