Emrick Liu
Emrick Liu

Reputation: 95

How to use expression list for mutate in dplyr?

I found that data masking that usually work in dplyr stop working when use together with !! operator.

Consider a simple example.

trans <- list(
  a = rlang::expr(val),
  b = rlang::expr(val*2)
)

df <- data.frame(name = c("a", "b"), val = 2:3)

Then, I would like to modify val column based on value from name using my list trans. Then, following code would not work.

library(dplyr)

df %>%
 rowwise() %>%
 mutate(val = !!trans[[ name ]]) 

It appears that name was not found. The code above would work if the a normal variable were used in place of name column in the dataframe.

How should I modify the code to make it work as intended? Thanks.

Upvotes: 1

Views: 128

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

You can use eval :

library(dplyr)

df %>%
  rowwise() %>%
  mutate(val_res = eval(trans[[name]]))

#  name    val val_res
#  <chr> <int>   <dbl>
#1 a         2       2
#2 b         3       6

Upvotes: 1

Related Questions