mutate_ functionality after deprecation

I have the following code which works with mutate_:

t1 <- data.frame(a=1:5,b=2:6,c=3:7)

my.eq <- "a + 2*b + c^2"

t1 %>% 
    mutate_(new_col=glue::glue("{my.eq}"))

Output:

  a b c new_col
1 1 2 3      14
2 2 3 4      24
3 3 4 5      36
4 4 5 6      50
5 5 6 7      66

However, with mutate, it dosen't work:

  a b c       new_col
1 1 2 3 a + 2*b + c^2
2 2 3 4 a + 2*b + c^2
3 3 4 5 a + 2*b + c^2
4 4 5 6 a + 2*b + c^2
5 5 6 7 a + 2*b + c^2

Now that mutate_ is deprecated, how can I get the same functionality?

Thanks
Menachem

this method is quite explicit

t1 %>% 
  mutate(new_col=glue::glue("{eval(parse(text=my.eq))}"))

# or without glue
t1 %>% 
  mutate(new_col=eval(parse(text=my.eq)))

Thanks! Works perfectly.

While we're with this example, how would you dynamically set the new column name?
This works, but is it the most explicit way?

new_col <- "d"

t1 %>% 
  mutate("{new_col}" := eval(parse(text=my.eq)))

You can use the "bang-bang" operator for these types of things. The trick is to say it as you type:

t1 %>% mutate(!!new_col := !!rlang::parse_expr(my.eq))

I think thats a fine approach, I don't know if theres a meaningful difference between that and alternatives.
but heres one alternative

t1 %>% 
  mutate( !!sym(new_col) := eval(parse(text=my.eq)))

oh, theres also this pattern which can be quite powerful

my.eq <- parse_exprs("a + 2*b +c^2")
names(my.eq) <- "d"
t1 %>% 
  mutate( !!!my.eq)

because it can be easily expanded

my.eqs <- parse_exprs(c("a + 2*b +c^2",
                       "a+3*b+c^3"))
names(my.eqs) <- c("d1","d2")
t1 %>% 
  mutate( !!!my.eqs)
1 Like

Hi. Thanks for your responses. Neat!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.