I find it hard to rename columns to functions using dplyr. I have already found useful posts about custom evaluation and use of enquo (for example, http://dplyr.tidyverse.org/articles/programming.html and Changing Result Variable Names in the dplyr Custom Function ). The ultimate goal is to use a function to summarize each group, and then rename the columns to something more meaningful than the original variable names.
Here is a simple example that works, except for the missing lines.
library(tidyverse)
myfunc <- function(df, groupvar, colvar, grouplab, collab) {
groupvar <- enquo(groupvar)
colvar <- enquo(colvar)
grouplab <- enquo(grouplab)
collab <- enquo(collab)
t <- df %>%
select(!!groupvar, !!colvar) %>%
group_by(!!groupvar, !!colvar) %>%
summarise(
Frequencies = length(!!colvar),
Percentages = length(!!colvar) / nrow(df)
) %>%
mutate(
Frequencies = scales::comma(Frequencies),
Percentages = scales::percent(Percentages)
)
...
}
myfunc <- (df = mtcars, groupvar = gear, colvar = cyl, grouplab = "Vehicle Gears", collab = "Vehicle Cylinders")
Outside of the functions, the corresponding part will simply read: mtcars <- mtcars %>% rename("Vehicle Cylinders" = cyl, "Vehicle Gears" = gear)
I need to understand how renaming works in a function compared to it. Any advice? I am open to suggestions.
UPDATE
. , . .
library(tidyverse)
library(xtable)
data(mtcars)
t_groupedfreqprop <- function(df, groupvar, colvar, grouplab, collab, plotname) {
groupvar2 <- rlang::sym(groupvar)
colvar2 <- rlang::sym(colvar)
grouplab <- rlang::sym(grouplab)
collab <- rlang::sym(collab)
t <- df %>%
select(!!groupvar2, !!colvar2) %>%
group_by(!!groupvar2, !!colvar2) %>%
summarise(
Frequencies = length(!!colvar2),
Percentages = length(!!colvar2) / nrow(df)
) %>%
mutate(
Frequencies = scales::comma(Frequencies),
Percentages = scales::percent(Percentages)
) %>%
rename(
!!grouplab := !!rlang::sym(groupvar2),
!!collab := !!rlang::sym(colvar2)
)
}
t_groupedfreqprop(df = mtcars, groupvar = "gear", colvar = "cyl", grouplab = "Vehicle Gears", collab = "Vehicle Cylinders")