I tried to translate a working dplyr-code into a function, but fail because of enquo()
/!!
.
The function is for a dataset with 160 variables and is applied repeatedly over a changing number of variables (sometimes over 3, like in the reprex, sometimes over 12, depending on the topic), the grouping variable ("ABTEIL") stays always the same. I read and tried many things about NSE (from SO, the vignette from dplyr.tidyverse.com etc), also had look at many other SO posts. I cannot locate the problem exactly.
# 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
I expect a summary over a specified subset of variables according to function (here sum) grouped by the fixed variable "ABTEIL" as shown above. Instead I get the error above.
EDIT: not sure how to tag/answer this: the answer of @aosmith solved the issue:
summarise_at(.vars = vars(vars),
.funs = sum)