我试图将有效的dplyr代码转换为函数,但是由于enquo()
/ !!
而失败。
该函数用于具有160个变量的数据集,并反复应用于变化数量的变量(有时超过3,例如在reprex中,有时超过12,具体取决于主题),分组变量(“ ABTEIL”)保持不变。 我阅读并尝试了许多有关NSE的内容(来自SO,来自dplyr.tidyverse.com的小插图等),还查看了许多其他SO帖子。我无法完全找到问题所在。
# Reprex
library(tidyverse)
# sample dataframe
ABTEIL <- c(rep(1:3, 4))
C1 <- c(sample(rep(0:1, 6)))
C2 <- c(sample(rep(1:0, 6)))
C3 <- c(sample(rep(1:0, 6)))
C4 <- c(sample(rep(1:0, 6)))
test_df <- tibble(ABTEIL, C1, C2, C3, C4)
# set of variables
test_vars <- c("C1", "C2", "C3")
# code with desired result
test_df %>%
group_by(ABTEIL) %>%
summarise_at(.vars = test_vars,
.funs = sum) %>%
column_to_rownames("ABTEIL") %>%
rownames_to_column() %>%
gather(Nr., value, -rowname) %>%
spread(rowname, value)
#> Nr. 1 2 3
#> 1 C1 1 2 3
#> 2 C2 2 3 1
#> 3 C3 2 2 2
# trying and putting it in a function
unit.wise.func <- function(df, vars){
vars <- enquo(vars)
df %>%
group_by(ABTEIL) %>%
summarise_at(.vars = !! vars,
.funs = sum) %>%
column_to_rownames("ABTEIL") %>%
rownames_to_column() %>%
gather(Nr., value, -rowname) %>%
spread(rowname, value)
}
unit.wise.func(df = test_df, vars = test_vars)
#> Error in is_quosure(e2): argument "e2" is missing, with no default
# sessioninfo
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.2
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] shiny_1.2.0 shurp2018_0.0.9000 kableExtra_1.0.1
naniar_0.4.1 forcats_0.3.0 stringr_1.3.1
[7] dplyr_0.8.0 purrr_0.3.0 readr_1.3.1
tidyr_0.8.2 tibble_2.0.99.9000 ggplot2_3.1.0
[13] tidyverse_1.2.1
我希望根据固定变量“ ABTEIL”分组的函数(此处为总和)对指定的变量子集进行汇总,如上所述。相反,我得到了上面的错误。
编辑:不确定如何标记/回答此问题:@aosmith的答案解决了该问题:
summarise_at(.vars = vars(vars),
.funs = sum)