7

通常使用 dplyr/tidyr,我可以通过否定实现排除

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

但是,目前,我希望以编程方式指定一些变量并将其排除在外,因此理想情况下

... %>% 聚集_(xVar,-yVar)

其中 xVar 和 yVar 是字符变量(例如,具有值 'x' 和 'y')。

函数的字符串版本是否根本不允许排除,还是有办法做到这一点?

-yVar这两个明显的罪魁祸首paste0('-', yVar)似乎都产生了错误。

4

1 回答 1

3

我最近遇到了同样的问题。我使用了自己计算包含列的解决方法。这并不完全令人满意,但我认为目前在gather_. 问题似乎出在select_vars_功能上。您可以使用 中的exclude选项规避它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"))
于 2015-03-09T09:24:49.937 回答