使用 `dplyr::count()` 的标准评估
standard eval with `dplyr::count()`
如何将字符向量传递给 dplyr::count()
。
library(magrittr)
variables <- c("cyl", "vs")
mtcars %>%
dplyr::count_(variables)
这很好用,但是 dplyr v0.8 抛出警告:
count_() is deprecated.
Please use count() instead
The 'programming' vignette or the tidyeval book can help you
to program with count() : https://tidyeval.tidyverse.org
我在 https://tidyeval.tidyverse.org/dplyr.html or other chapters of the current versions of the tidyeval book and Programming with dplyr 中没有看到引用名称或 dplyr::count()
的标准评估示例。
阅读此文档后我的两个最佳猜测 是
mtcars %>%
dplyr::count(!!variables)
mtcars %>%
dplyr::count(!!rlang::sym(variables))
抛出这两个错误:
Error: Column <chr>
must be length 32 (the number of rows) or one,
not 2
Error: Only strings can be converted to symbols
要从字符串创建符号列表,您需要 rlang::syms
(而不是 rlang::sym
)。要取消引用列表或向量,您需要使用 !!!
(而不是 !!
)。以下将起作用:
library(magrittr)
variables <- c("cyl", "vs")
vars_sym <- rlang::syms(variables)
vars_sym
#> [[1]]
#> cyl
#>
#> [[2]]
#> vs
mtcars %>%
dplyr::count(!!! vars_sym)
#> # A tibble: 5 x 3
#> cyl vs n
#> <dbl> <dbl> <int>
#> 1 4 0 1
#> 2 4 1 10
#> 3 6 0 3
#> 4 6 1 4
#> 5 8 0 14
也许你可以试试
mtcars %>%
group_by(cyl, vs) %>%
tally()
这给出了
# A tibble: 5 x 3
# Groups: cyl [3]
cyl vs n
<dbl> <dbl> <int>
1 4 0 1
2 4 1 10
3 6 0 3
4 6 1 4
5 8 0 14
如何将字符向量传递给 dplyr::count()
。
library(magrittr)
variables <- c("cyl", "vs")
mtcars %>%
dplyr::count_(variables)
这很好用,但是 dplyr v0.8 抛出警告:
count_() is deprecated. Please use count() instead
The 'programming' vignette or the tidyeval book can help you to program with count() : https://tidyeval.tidyverse.org
我在 https://tidyeval.tidyverse.org/dplyr.html or other chapters of the current versions of the tidyeval book and Programming with dplyr 中没有看到引用名称或 dplyr::count()
的标准评估示例。
阅读此文档后我的两个最佳猜测
mtcars %>%
dplyr::count(!!variables)
mtcars %>%
dplyr::count(!!rlang::sym(variables))
抛出这两个错误:
Error: Column
<chr>
must be length 32 (the number of rows) or one, not 2Error: Only strings can be converted to symbols
要从字符串创建符号列表,您需要 rlang::syms
(而不是 rlang::sym
)。要取消引用列表或向量,您需要使用 !!!
(而不是 !!
)。以下将起作用:
library(magrittr)
variables <- c("cyl", "vs")
vars_sym <- rlang::syms(variables)
vars_sym
#> [[1]]
#> cyl
#>
#> [[2]]
#> vs
mtcars %>%
dplyr::count(!!! vars_sym)
#> # A tibble: 5 x 3
#> cyl vs n
#> <dbl> <dbl> <int>
#> 1 4 0 1
#> 2 4 1 10
#> 3 6 0 3
#> 4 6 1 4
#> 5 8 0 14
也许你可以试试
mtcars %>%
group_by(cyl, vs) %>%
tally()
这给出了
# A tibble: 5 x 3
# Groups: cyl [3]
cyl vs n
<dbl> <dbl> <int>
1 4 0 1
2 4 1 10
3 6 0 3
4 6 1 4
5 8 0 14