R: Using a string as an argument to mutate verb in dplyr

后端 未结 2 493
执念已碎
执念已碎 2020-12-01 19:19

I am building a shiny app which needs to allow users to define new variables for plotting. Specifically I want to allow users to define an expression to be used in mutate ve

2条回答
  •  时光说笑
    2020-12-01 19:49

    Package friendlyeval is a simplified interface to tidy eval that tries to make things a bit more straight forward in cases like these.

    Splitting your string in two, you obtain part of the string you wish to use as a column name and part of a string you wish to use as an expression. So you could write:

    library(friendlyeval)
    library(dplyr)
    lhs <- "Petal.ratio"
    rhs <- "Petal.Length/Petal.Width"
    
    iris_mutated3 <- 
      iris %>% 
      mutate(!!treat_string_as_col(lhs) := !!treat_string_as_expr(rhs))
    head(iris_mutated3)
    

    By using the function on the lhs, you gain checking that lhs can be parsed as plain column name.

    friendlyeval code can be converted to plain tidy eval code at any time using an RStudio addin.

提交回复
热议问题