How to evaluate expressions inside mutate()

Viewed 1002

I am trying to evaluate expressions inside a mutate() command and I'm getting errors. Here's what my code looks like right now:

depvar <- "foo"
transformedvars[1] <- "mean(bar)"

dataset %>% mutate(paste0("t", depvar) = transformedvars[1])

I want to use mutate() to create a column called tfoo and have it take as values the result of calling up mean(bar), where bar is another column in my data.

The error I am getting is:

Error: unexpected '=' in: "dataset %>% mutate(paste0("t", depvar) ="

2 Answers

This requires rlang. First, I create a data frame:

df <- data.frame(bar = runif(10))

#            bar
# 1  0.549319057
# 2  0.351898657
# 3  0.326850457
# 4  0.951580599
# 5  0.712514111
# 6  0.425802253
# 7  0.240621368
# 8  0.002803366
# 9  0.471586186
# 10 0.387040517

Next, I state my variable name and transformation:

dep_var <- "foo"
tran_var <- "mean(bar)"

Finally, I use !! to unquote the string I create with paste and the parsed string from parse_quosure.

df %>% mutate(!!paste("t", dep_var, sep = "") := !!parse_quosure(tran_var))

#            bar      tfoo
# 1  0.549319057 0.4420017
# 2  0.351898657 0.4420017
# 3  0.326850457 0.4420017
# 4  0.951580599 0.4420017
# 5  0.712514111 0.4420017
# 6  0.425802253 0.4420017
# 7  0.240621368 0.4420017
# 8  0.002803366 0.4420017
# 9  0.471586186 0.4420017
# 10 0.387040517 0.4420017

Edit

Checking the documentation, it looks like parse_quosure was 'soft-deprecated' and so the following may be more up-to-date:

df %>% mutate(!!paste("t", dep_var, sep = "") := !!parse_quo(tran_var, env = caller_env()))

I don't know why you want to use Tidyverse code here at all, when base R code is much clearer:

newname <- paste0("t", depvar)
df[, newname] <- with(df, eval(parse(text = transformedvars[1])))

It could all be done in one line as

df[, paste0("t", depvar)] <- with(df, eval(parse(text = transformedvars[1])))

but I think the two line version is easier to read.

Related