1

I want to make a function where tidy-select is going to be called (as part of pivot_longer), and I wanted to be able to pass a string of column names to the function so that it isn't hard-coded.

For example

column<- c("c1","c2")
df %>%
    pivot_longer(cols = column,...)

As far as I can tell, you can't do this because tidy-select will only take the names directly

For example

pivot_longer(df, cols = c(c1,c2),...)

Any tips on what I want to do?

NAccumbens
  • 33
  • 4
  • You could simply use `df %>% pivot_longer(cols = column)` and it wlll also work with a warning – akrun Jul 31 '20 at 22:03

1 Answers1

2

You can use all_of:

pivot_longer(df, cols = all_of(column),...)

From the tidyr manual:

If you have a character vector of column names, use all_of() or any_of(), depending on whether or not you want unknown variable names to cause an error, e.g unnest(df, all_of(vars)), unnest(df, -any_of(vars)).

slava-kohut
  • 4,203
  • 1
  • 7
  • 24