Search code examples
rrlangtidyeval

Transform string of expression into quotable expression


How do I transform a string of expression into a quotable expression?

Example: This is the result I want:

mutate(mtcars,answer=wt+wt)
# mpg   cyl disp  hp  drat wt    qsec   vs  am   gear carb    answer
# 1  21.0  6   160.0 110 3.90 2.620 16.46  0   1    4    4    5.240
# 2  21.0  6   160.0 110 3.90 2.875 17.02  0   1    4    4    5.750
# 3  22.8  4   108.0  93 3.85 2.320 18.61  1   1    4    1    4.640
# 4  21.4  6   258.0 110 3.08 3.215 19.44  1   0    3    1    6.430
# 5  18.7  8   360.0 175 3.15 3.440 17.02  0   0    3    2    6.880
# 6  18.1  6   225.0 105 2.76 3.460 20.22  1   0    3    1    6.920 
... 

Here's the function I am writing:

f<-function(df,string_expression){
    se<-enexpr(string_expression)
    mutate(df,answer=!!se)
}

It will work if I use the following functional call:

f(mtcars,wt+wt)
# mpg   cyl disp  hp  drat wt    qsec   vs  am   gear carb    answer
# 1  21.0  6   160.0 110 3.90 2.620 16.46  0   1    4    4    5.240
# 2  21.0  6   160.0 110 3.90 2.875 17.02  0   1    4    4    5.750
# 3  22.8  4   108.0  93 3.85 2.320 18.61  1   1    4    1    4.640
# 4  21.4  6   258.0 110 3.08 3.215 19.44  1   0    3    1    6.430
# 5  18.7  8   360.0 175 3.15 3.440 17.02  0   0    3    2    6.880
# 6  18.1  6   225.0 105 2.76 3.460 20.22  1   0    3    1    6.920 
... 

However, I would like to provide the expression as a string, so I must use the following function call:

f(mtcars,'wt+wt')
#    mpg   cyl disp  hp  drat wt    qsec   vs  am   gear carb answer
# 1  21.0  6   160.0 110 3.90 2.620 16.46  0   1    4    4    wt+wt
# 2  21.0  6   160.0 110 3.90 2.875 17.02  0   1    4    4    wt+wt
# 3  22.8  4   108.0  93 3.85 2.320 18.61  1   1    4    1    wt+wt
# 4  21.4  6   258.0 110 3.08 3.215 19.44  1   0    3    1    wt+wt
# 5  18.7  8   360.0 175 3.15 3.440 17.02  0   0    3    2    wt+wt
...

How do I make it (either change the function definition or function call) to get the result I want?

What I have tried:

  • I have tried to sym(string_expression) -- didn't work.

  • I have tried to quo(string_expression) -- didn't work.

Thank you!


Solution

  • You could change your f function to something this:

    f<-function(df,string_expression){
    mutate(df, answer = eval(parse(text = string_expression)))
    }
    
    head(f(mtcars,'wt+wt'))
       mpg cyl disp  hp drat    wt  qsec vs am gear carb answer
    1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4   5.24
    2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4   5.75
    3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1   4.64
    4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1   6.43
    5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   6.88
    6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1   6.92