0

See example:

df <- data.frame(month=rep(1:3,2),
                 student=rep(c("Amy", "Bob"), each=3),
                 A=c(9, 7, 6, 8, 6, 9),
                 B=c(6, 7, 8, 5, 6, 7))
cnames<-function(){c(month="month",student="student")}

When wrapping cnames() into c() the call to tidyr::gather works:

df2 <- df %>% 
  gather(variable, value, -c(cnames()))

but it fails when i call it with cnames() or even (cnames()) only :

df2 <- df %>% 
  gather(variable, value, -(cnames()))

i.e.

> df2 <- df %>% 
+   gather(variable, value, -(cnames()))
Error in -(cnames()) : invalid argument to unary operator

I am guessing this has something to do with NSE but what exactly?

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
witek
  • 984
  • 1
  • 8
  • 25
  • Why are you defining `cnames` as a function and not as vector and simly do `cnames <- c('month', 'student'); df %>% gather(var, val, -cnames)`? – Sotos Apr 13 '18 at 08:06
  • It is strange that I get the same error after installing to 0.8.0. For me `df %>% gather(variable, value, -one_of(cnames()))` works as expected – akrun Apr 13 '18 at 08:14
  • @akrun indeed strange. Maybe conflicts? Try restarting your session – Sotos Apr 13 '18 at 08:25
  • @Sotos Why? one possible Answer : `cnames` is a function which computes the column names given the dataframe and an algorithm. A different, you have an OO application. etc etc. – witek Apr 13 '18 at 10:06
  • Yes, ...Why... You have the names set in the function. However, If that is the case, use the function to create the vector and then do the `gather` part (i.e. `v1 = cnames(); df %>% gather(var, val, -v1)` – Sotos Apr 13 '18 at 10:09
  • @Sotos, You did not understand the question. The question is NOT how to get it working -( I did even provide an example when it works). I would like to understand why it does not when passing cnames() directly? Any ideas? – witek Apr 13 '18 at 14:03

1 Answers1

2

I believe the 'proper' way of doing it in current tidyverse/tidyselect would be...

df %>% gather(variable, value, -(!! cnames()))

The reason df %>% gather(variable, value, -c(cnames())) works is because c() is specifically handled differently than usual in tidyselect. See string coercion affects c() #37

df %>% gather(variable, value, -(cnames())) does not work because the entire expression evalutes (including the -), so you get the same error as if you run simply -(cnames())

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56