I'm running into an issue passing a column being created in mutate to the the group_by function.
here is some example data:
set.seed(42) ## for sake of reproducibility
w2_test <- data.frame(id=1:607,
wave = "W2",
tech =floor(runif(607, 1, 6)))
This function does recoding of Likert scales
recoding_1_fn <- function(var_name) {
var_name_ <- case_when(
var_name %in% c(1, 2, 3, 6) ~ "disagree",
var_name %in% c(4, 5) ~ "agree",
TRUE ~ NA
)
}
and this function attempts to summarize n by the recoded scales above
summary_w2_fn <- function(df, w2_name, w3_name, suffix = "recoded") {
df %>%
rename({{w3_name}} := {{w2_name}}) %>%
count(wave, {{w3_name}}) %>%
drop_na() %>%
mutate("{{w3_name}}_{suffix}" := recoding_1_fn({{w3_name}})) %>%
group_by(wave, "{{w3_name}}_{suffix}") %>%
summarise(n = sum(n)) %>%
rename("{{w3_name}}" := "{{w3_name}}_{suffix}")
}
when called This above function works up until the mutate function
w2 %>% summary_w2_fn(tech, W3_SUS_4)
and I get a dataset that looks like this:
If I let it run to the group_by, it won't recognize the column "{{w3_name}}_{suffix}" and I get the following
I've tried a number of enquo, quos, !!, etc. but really at random, since I'm stuck, nothing has worked.
If there a way that I can pass the column being created in mutate to the next function?
You help appreciated.
Thanks
Untested since you didn't provide a reprex:
summary_w2_fn <- function(df, w2_name, w3_name, suffix = "recoded") {
recoded_name <- rlang::englue("{{w3_name}}_{suffix}")
df %>%
rename({{w3_name}} := {{w2_name}}) %>%
count(wave, {{w3_name}}) %>%
drop_na() %>%
mutate("{recoded_name}" := recoding_1_fn({{w3_name}})) %>%
group_by(wave, .data[[recoded_name]]) %>%
summarise(n = sum(n))
}
I removed the last expression because it had the structure of a filter()
but it was a call to rename()
, something looks wrong.