3

data is a data.frame containing: date, a, b, c, d columns. Last 4 is numeric

Y.columns <- c("a")
X.columns <- c("b","c","d")

what i need:

data.mutated <- data %>% 
  mutate(Y = a, X = b+c+d) %>%
  select(date,Y,X)

but i would like to pass mutate arguments from character vector, i tried the following:

Y.string <- paste(Y.columns, collapse='+')

X.string <- paste(X.columns, collapse='+')

data.mutated <- data %>% 
  mutate(Y = UQ(Y.string), X = UQ(X.string)) %>%
  select(date,Y,X)

But it didn't work. any help is appreciated.

www
  • 38,575
  • 12
  • 48
  • 84
Mari
  • 165
  • 1
  • 3
  • 8

1 Answers1

3

To use tidyeval with UQ, you need to first parse your expressions to a quosure with parse_quosure from rlang (Using mtcars as example, since OP's question is not reproducible):

Y.columns <- c("cyl")
X.columns <- c("disp","hp","drat")

Y.string <- paste(Y.columns, collapse='+')

X.string <- paste(X.columns, collapse='+')

library(dplyr)
library(rlang)

mtcars %>% 
  mutate(Y = UQ(parse_quosure(Y.string)), 
         X = UQ(parse_quosure(X.string))) %>%
  select(Y,X)

or with !!:

mtcars %>% 
  mutate(Y = !!parse_quosure(Y.string), 
         X = !!parse_quosure(X.string)) %>%
  select(Y,X)

Result:

   Y      X
1  6 273.90
2  6 273.90
3  4 204.85
4  6 371.08
5  8 538.15
6  6 332.76
7  8 608.21
8  4 212.39
9  4 239.72
10 6 294.52
...

Note:

mutate_ has now deprecated, so I think tidyeval with quosure's and UQ is the new way to go.

acylam
  • 18,231
  • 5
  • 36
  • 45
  • 4
    Well that's what Hadley Wickham says... but honestly it's so complicated, while the whole interest of dplyr is that it's so simple and intuitive... so far the only benefit I've found in (partially) understanding this new way of doing things is to understand some answers on stack overflow. – moodymudskipper Nov 09 '17 at 17:54