Struggling with Non Standard Evaluation

June 16, 2016
By

(This article was first published on /mgritts_, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

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)