2

I want to use pivot_longer within a function that takes arbitrary arguments. I tried this, which doesn't work:

tolong <- function(x, ...) {
  x %>%
    pivot_longer(cols = ...)
}

tolong(pheno, fev1, fvc)

Error in build_longer_spec(data, !!cols, names_to = names_to, values_to = values_to,  : 
  object 'fvc' not found 

I also tried cols = c(...), cols = vars(...) and cols = list(...), none of which work. The only way I have found so far to get it to work is this:

tolong <- function(x, ...) {
  x %>%
    pivot_longer(cols = vars(...) %>% as.character %>% sub("~", "", .)) 
}

Surely there must be a neater way?

flimbar
  • 115
  • 5

1 Answers1

2

Use enquos to capure ellipses as column input

tolong <- function(x, ...) {
  vars <- enquos(...)
  x %>%
    pivot_longer(cols = c(!!!vars))
}


tolong(anscombe, y1, y2, y3, y4)

# # A tibble: 44 x 6
#       x1    x2    x3    x4 name  value
#    <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
#  1    10    10    10     8 y1     8.04
#  2    10    10    10     8 y2     9.14
#  3    10    10    10     8 y3     7.46
#  4    10    10    10     8 y4     6.58
#  5     8     8     8     8 y1     6.95
#  6     8     8     8     8 y2     8.14
#  7     8     8     8     8 y3     6.77
#  8     8     8     8     8 y4     5.76
#  9    13    13    13     8 y1     7.58
# 10    13    13    13     8 y2     8.74
# # … with 34 more rows
nurandi
  • 1,588
  • 1
  • 11
  • 20
  • I was trying to move away from the tidyeval quote-unquote style in favour of rlang curly curly {{ }} style, but I see it is still necessary to use quote-unquote for ellipses (https://stackoverflow.com/questions/56936372/curly-curly-tidy-evaluation-and-modifying-inputs-or-their-names) until rlang includes a {{{ }}} operator. – flimbar Apr 03 '20 at 17:42