Struggling with Non Standard Evaluation

[This article was first published on /mgritts_, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

All the functions in dplyr (and many of the packages in the “hadleyverse”) use Non Standard Evaluation (NSE). NSE is extremely handy and generally reduces the amount of typing required. However functions that use NSE aren’t always intuitive to use. I mostly run into this issue when using dplyr in a Shiny applications. Most recently I’ve run into this issue attempting to dynamically filter a data.frame on different columns. This gist has a sample of the data I’m working with.

In base R filtering a data.frame is fairly straight forward. However a fairly intuitive attempt to use dplyr::filter doesn’t work, instead returning an empty data.frame.

x <- dat[dat$HuntUnit == 262, ]
col <- 'HuntUnit'
val <- 262
x1 <- dat[dat[, col] == val, ]
identical(x, x1)
x2 <- filter(dat, col == val)

In order to evaluate this expression use the lazyeval::interp function with filter_.

x <- filter(dat, HuntUnit == 262)
# filter criteria
criteria <- lazyeval::interp(~x == val, .values = list(x = as.name(col)))
x1 <- filter_(dat, criteria)
identical(x, x1)

In the Shiny application I have a drop down input and text input to filter a data.frame. The drop down input chooses the column to filter and the text input is the criteria for the filter. I haven’t been able to get this Standard Evaluation version to work with a database backend. The dplyr vignette mentions NSE is important for database backends. dplyr::*_ functions are Standard Evaluation equivalents, I’m not certain they’ll work for databases.

For more information about NSE look at the Advanced R book and this quick post by Carl Boettiger

To leave a comment for the author, please follow the link and comment on their blog: /mgritts_.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)