dplyr mutate using dynamic variable name while respecting group_by

I actually did not know much about pluck, so I don't know what went wrong, but I would go for this and this works:

iris %>% group_by(Species) %>% 
  mutate(
    !! varname :=
      mean(!!as.name(varname), na.rm = T) / 
      max(sd(!!as.name(varname)),
          minsd[varname])
 )

Let me know if this isn't what you were looking for.


The other answer is obviously the best and it also solved a similar problem that I have encountered. For example, with !!as.name(), there is no need to use group_by_() (or group_by_at or arrange_() (or arrange_at()).

However, another way is to replace pluck(iris,varname) in your code with .data[[varname]]. The reason why pluck(iris,varname) does not work is that, I suppose, iris in pluck(iris,varname) is not grouped. However, .data refer to the tibble that executes mutate(), and so is grouped.

An alternative to as.name() is rlang::sym() from the rlang package.

Tags:

R

Dplyr