Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr mutate using character vector of column names

Tags:

r

dplyr

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.

like image 461
Mari Avatar asked Oct 21 '25 23:10

Mari


1 Answers

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.

like image 72
acylam Avatar answered Oct 23 '25 16:10

acylam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!