Search code examples
rselectdplyrnse

dplyr evaluation: select() vs. mutate()


Can anyone explain why the dplyr approach that works with select() does not work with mutate()?

Minimal Working Example:

data <- as.tibble(cbind(c(1,2,3,4),c(5,6,7,8)))
func <- function(data, var){
  data %>% select(!!var)
}
func2 <- function(data, var){
  data %>% mutate(!!var/10)
}

In this MWE, func(data,quo(V1)) works. func2(data, quo(V1)) doesn't, it spits out Error in var/10 : non-numeric argument to binary operator. That is, the very same strategy that allows select() to correctly evaluate "var" as "V1", does not allow mutate() to do the same.

Is there any reason, any work around?


Solution

  • Just small fix is needed, specify the name of new column and add brackets.

    func2 <- function(data, var){ data %>% mutate(V3 = (!!var)/10) }