正在尝试排除
-
倍数
调用中的列
tidyr::gather()
-
通过
字符向量
参数(的输出
shiny::selectInput
)而不是via
...
-
在a中
编程的
方法
我如何使用tidy eval功能做到这一点?
由于我通过一个函数参数传递多个列名,所以我认为需要使用
!!!
(取消拼接)而不是
!!
如中所示
Programming with dplyr
.但这似乎与
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
但是
我想通过
仅有一个的
参数(如在shiny应用程序中,它将通过
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
编辑
在莱昂内尔的帮助下,我把它拼凑起来:
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年4月26日
reprex package
(v0.2.0)。