7

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.

durron597
  • 31,968
  • 17
  • 99
  • 158
daj
  • 6,962
  • 9
  • 45
  • 79
  • 1
    I think this is a good use for `matches`, see the examples at the bottom of `?select`. I'm surprised you are using `gather()` as your example, it's in `tidyr`, not `dplyr`. – Gregor Thomas Mar 07 '15 at 04:54
  • amended to tidyr/dplyr – daj Mar 07 '15 at 05:39
  • Perhaps you could also edit it to a valid `gather` call, with example data? After `data`, the next two `gather` arguments are `key` and `value`... I don't think "not column y" is a good argument for `value`. (Or use a different function, I'm having trouble thinking of a use case for a negative column in `gather()`... an example with built-in data would make it clear). – Gregor Thomas Mar 07 '15 at 05:44
  • I'm not a dplyr/tidyr user but I would remind you that the numeric-negation operator is not effective with character vectors when used with the two argument version of "[". You would need to use the logical negation operator `!` with that function. You do not offer a test case which may explain the lack of attention to this question so far. Perhaps if you edit it to have a complete example it might get more attention. – IRTFM Mar 07 '15 at 16:16

1 Answers1

3

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"))
shadow
  • 21,823
  • 4
  • 63
  • 77