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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With