cephalopod
cephalopod

Reputation: 1906

How to use a variable with "gather" and "select"

I would like to assign a text to a variable and then use that variable within my pipeline. I extensively use gather and select.

In the example below, I want to be able to use x within my pipeline code:

library(tidyverse)

mtcars %>% head

mtcars %>% 
  gather(type, value, mpg:am) %>% head

mtcars %>% select(mpg:am) %>% head

This the variable I want to use

x <- "mpg:am"

None of what I have tried has worked

mtcars %>% 
  gather(type, value, get(x)) %>% head


mtcars %>% 
  gather(type, value, !!rlang::sym(x)) %>% head


mtcars %>% select(x) %>% head
mtcars %>% select(!!rlang::sym(x)) %>% head

Any ideas?

Upvotes: 3

Views: 237

Answers (1)

akrun
akrun

Reputation: 887981

We can quote/quo it and then evaluate with !!

x <- quo(mpg:am)
out1 <- mtcars %>%
            gather(type, value, !! x)

Checking the output with

out2 <- mtcars %>%
           gather(type, value, mpg:am)
identical(out1, out2)
#[1] TRUE

Upvotes: 2

Related Questions