试图排除
-
multiple调用中的列
tidyr::gather()
- 它们通过a作为我的函数的输入字符向量参数(输出
shiny::selectInput
)而不是通过...
- in a 程序化的 way
我该如何使用整洁的评估功能来做到这一点?
由于我通过单个函数参数传递多个列名称,我认为我需要使用!!!
(取消引号拼接)而不是!!
如中所述使用 dplyr 编程 https://dplyr.tidyverse.org/articles/programming.html#unquote-splicing。但这似乎不太好用tidyselect::vars_select()
似乎-
造成了麻烦。
这是我想做的基本事情:
library(magrittr)
gather_data_1 <- function(dat, ...) {
dat %>% tidyr::gather("key", "value", ...)
}
mtcars %>% gather_data_1(-mpg, -cyl) %>% head()
#> mpg cyl key value
#> 1 21.0 6 disp 160
#> 2 21.0 6 disp 160
#> 3 22.8 4 disp 108
#> 4 21.4 6 disp 258
#> 5 18.7 8 disp 360
#> 6 18.1 6 disp 225
But我想通过single参数(就像在闪亮的应用程序中它将通过input$<select_input_id>
以及):
gather_data_2 <- function(dat, exclude) {
exclude <- rlang::syms(exclude)
dat %>% tidyr::gather("key", "value", -!!!exclude)
}
mtcars %>% gather_data_2(exclude = c("mpg", "cyl"))
#> Error: Can't use `!!!` at top level
然后我试着看看是否-
问题是:
gather_data_3 <- function(dat, exclude) {
exclude <- rlang::syms(exclude)
dat %>% tidyr::gather("key", "value", !!!exclude)
}
mtcars %>% gather_data_3(exclude = c("mpg", "cyl")) %>% head()
#> disp hp drat wt qsec vs am gear carb key value
#> 1 160 110 3.90 2.620 16.46 0 1 4 4 mpg 21.0
#> 2 160 110 3.90 2.875 17.02 0 1 4 4 mpg 21.0
#> 3 108 93 3.85 2.320 18.61 1 1 4 1 mpg 22.8
#> 4 258 110 3.08 3.215 19.44 1 0 3 1 mpg 21.4
#> 5 360 175 3.15 3.440 17.02 0 0 3 2 mpg 18.7
#> 6 225 105 2.76 3.460 20.22 1 0 3 1 mpg 18.1
这似乎有效。
然后我试图得到-
到实际的符号名称中,但这不起作用(至少是我尝试的方式;-)):
gather_data_4 <- function(dat, exclude) {
exclude <- rlang::syms(sprintf("-%s", exclude))
dat %>% tidyr::gather("key", "value", !!!exclude)
}
mtcars %>% gather_data_4(exclude = c("mpg", "cyl"))
#> Error in .f(.x[[i]], ...): object '-mpg' not found
[1]: https://dplyr.tidyverse.org/articles/programming.html#unquote-splicing
EDIT
在莱昂内尔的帮助下,我能够将其拼凑起来:
gather_data_6 <- function(dat, exclude) {
dat %>% tidyr::gather("key", "value", -c(rlang::UQS(exclude)))
}
mtcars %>% gather_data_6(exclude = c("mpg", "cyl")) %>% head()
#> mpg cyl key value
#> 1 21.0 6 disp 160
#> 2 21.0 6 disp 160
#> 3 22.8 4 disp 108
#> 4 21.4 6 disp 258
#> 5 18.7 8 disp 360
#> 6 18.1 6 disp 225
甚至简化:
gather_data_7 <- function(dat, exclude) {
dat %>% tidyr::gather("key", "value", -c(!!!exclude))
}
mtcars %>% gather_data_7(exclude = c("mpg", "cyl")) %>% head()
#> mpg cyl key value
#> 1 21.0 6 disp 160
#> 2 21.0 6 disp 160
#> 3 22.8 4 disp 108
#> 4 21.4 6 disp 258
#> 5 18.7 8 disp 360
#> 6 18.1 6 disp 225
创建于 2018-04-26代表包 https://github.com/tidyverse/reprex(v0.2.0)。