Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclusions with '-' when using string versions (underscore suffix such as gather_()) of dplyr/tidyr functions

Tags:

r

dplyr

tidyr

Normally with dplyr/tidyr, I can achieve exclusions with negation

... %>% gather(x, -y)

However, currently, I want some variables to be specified programmatically and be an exclusion, so ideally

... %>% gather_(xVar, -yVar)

where xVar and yVar are character variables (say, with values 'x' and 'y').

Are exclusions simply disallowed with the string versions of functions, or is there a way to do them?

Both of the obvious culprits -yVar and paste0('-', yVar) seem to produce errors.

like image 595
daj Avatar asked Mar 07 '15 04:03

daj


1 Answers

I had the same problem recently. I used the workaround of calculating the included columns myself. This is not entirely satisfactory, but I don't think that this is currently possible with gather_. The issue seems to be in the select_vars_ function. You can circumvent it using the exclude option in select_vars_.

# creating sample data from example in gather
stocks <- data.frame(
  time = as.Date('2009-01-01') + 0:9,
  X = rnorm(10, 0, 1),
  Y = rnorm(10, 0, 2),
  Z = rnorm(10, 0, 4)
)
# original call using gather
gather(stocks, stock, price, -time)
# calculating select_vars yourself
stocks %>% gather_("stock", 
                   "price", 
                   names(.)[!"time" == names(.)])
# using exclude in select_vars_
stocks %>% gather_("stock", 
                   "price", 
                   select_vars_(names(.), 
                                names(.), 
                                exclude = "time"))
like image 166
shadow Avatar answered Nov 15 '22 09:11

shadow