How to pass dynamic column names in dplyr into custom function? How to pass dynamic column names in dplyr into custom function? r r

How to pass dynamic column names in dplyr into custom function?


Using the latest version of dplyr (>=0.7), you can use the rlang !! (bang-bang) operator.

library(tidyverse)from <- "Stand1971"to <- "Stand1987"data %>%  mutate(diff=(!!as.name(from))-(!!as.name(to)))

You just need to convert the strings to names with as.name and then insert them into the expression. Unfortunately I seem to have to use a few more parenthesis than I would like, but the !! operator seems to fall in a weird order-of-operations order.

Original answer, dplyr (0.3-<0.7):

From that vignette (vignette("nse","dplyr")), use lazyeval's interp() function

library(lazyeval)from <- "Stand1971"to <- "Stand1987"data %>%  mutate_(diff=interp(~from - to, from=as.name(from), to=as.name(to)))


You can use .data inside dplyr chain now.

library(dplyr)from <- "Stand1971"to <- "Stand1987"data %>% mutate(diff = .data[[from]] - .data[[to]])

Another option is to use sym with bang-bang (!!)

data %>% mutate(diff = !!sym(from) - !!sym(to))

In base R, we can use :

data$diff <- data[[from]] - data[[to]]