Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 verb. The server receives the expression as text and I am wondering how to make mutate execute it in dplyr 0.7. I can make it work (partially) using mutate_ but it is deprecated now. It also defines the new column name as the entire expression rather than the new variable

Here is a reproducible example:

input_from_shiny <- "Petal.ratio = Petal.Length/Petal.Width"
iris_mutated <- iris %>% mutate_(input_from_shiny)

This gives the following

> head(iris_mutated)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species Petal.ratio = Petal.Length/Petal.Width
1          5.1         3.5          1.4         0.2  setosa                                   7.00
2          4.9         3.0          1.4         0.2  setosa                                   7.00
3          4.7         3.2          1.3         0.2  setosa                                   6.50
4          4.6         3.1          1.5         0.2  setosa                                   7.50
5          5.0         3.6          1.4         0.2  setosa                                   7.00
6          5.4         3.9          1.7         0.4  setosa                                   4.25

Technically, I can use regular expression to extract new variable name from the string and rename the new column accordingly, but I am wondering what is the correct way to implement it using latest dplyr version (was reading https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html, but could not figure it out)

like image 590
Sasha Avatar asked Mar 24 '18 21:03

Sasha


1 Answers

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.

like image 164
MilesMcBain Avatar answered Sep 21 '22 19:09

MilesMcBain