3

I'm wondering if there is a DRY way to write the following pipe:

library(tidyverse)
data(iris)
iris %>% arrange(Sepal.Width, Species) %>% select(Sepal.Width, Species)

This works perfectly but if a change in the code is needed, I have two places to edit.

Is there any way to rewrite the code in such a way that the variables are listed only once in the pipeline?

I'd hope there is a way I can store the variable list v and then call:

iris %>% arrange(v) %>% select(v)

I've tried to use quote, Sym, and many other functions of Non Standard Evaluation in order to store the list of variables to no avail.


All those answers were unhelpful for this problem:

r - how to use a variable in a variable

Using a variable to refer to another variable in R?

R expression variable list

r - how to use a variable in a variable

xihh
  • 169
  • 2
  • 12
  • There is a _big_ difference between DRY and what you're talking about. – hrbrmstr Nov 24 '18 at 02:30
  • 2
    Possible duplicate of [Pass a vector of variable names to arrange() in dplyr](https://stackoverflow.com/questions/26497751/pass-a-vector-of-variable-names-to-arrange-in-dplyr) – Len Greski Nov 24 '18 at 03:30
  • Yes, that solved my problem. I think that question should reworded more generally so that It can be found quickly. – xihh Nov 24 '18 at 18:46

2 Answers2

0

Yes, it's a duplicate of Pass a vector of variable names to arrange() in dplyr...

library(tidyverse)
data(iris)
varList <- c("Sepal.Width","Species")
iris %>% arrange_(.dots=varList) %>% select_(.dots=varList)

...and the output:

> iris %>% arrange_(.dots=varList) %>% select_(.dots=varList)
    Sepal.Width    Species
1           2.0 versicolor
2           2.2 versicolor
3           2.2 versicolor
4           2.2  virginica
5           2.3     setosa
6           2.3 versicolor
7           2.3 versicolor
8           2.3 versicolor
9           2.4 versicolor
10          2.4 versicolor
11          2.4 versicolor
12          2.5 versicolor
13          2.5 versicolor
14          2.5 versicolor
15          2.5 versicolor
16          2.5  virginica
17          2.5  virginica
18          2.5  virginica
19          2.5  virginica
20          2.6 versicolor
21          2.6 versicolor
22          2.6 versicolor
23          2.6  virginica
24          2.6  virginica
...
Len Greski
  • 10,505
  • 2
  • 22
  • 33
0

I think what you looking for is:

library(tidyverse)
vars <- quos(Sepal.Width, Species)

iris %>% arrange(!!!vars) %>% select(!!!vars)

I assumed you meaned select rather than filter as your question stated since iris %>% arrange(Sepal.Width, Species) %>% filter(Sepal.Width, Species) throws an error

davsjob
  • 1,882
  • 15
  • 10