I'm having trouble unquoting variable created by a function (with a prefix if it matters) for subsequent usage later in the function. enquo doesn't seem to work, but I'm sure I'm doing something dumb. (I'm new to tidyeval.
library(survey)
library(ggplot2)
library(dplyr)
data(api)
names( apistrat)
apistrat <- apistrat %>% as_survey_design(ids = 1, fpc = fpc)
test_func <- function(var) {
apistrat %>% mutate(col.grad=as.factor(col.grad)) %>% group_by(col.grad) %>%
summarise("mean_{{var}}" := survey_mean({{ var }}, na.rm=TRUE)) %>%
mutate("ub_mean_{{var}}" :=
"mean_{{var}}_se" * 1.96 + "mean_{{var}}") #Think I need to unquote for this line so it's evaluated
}
test_func(meals)
#Tried this, which didn't work
test_func <- function(var) {
apistrat %>% mutate(col.grad=as.factor(col.grad)) %>% group_by(col.grad) %>%
summarise("mean_{{var}}" := survey_mean({{ var }}, na.rm=TRUE)) %>%
mutate("ub_mean_{{var}}" :=
enquo("mean_{{var}}_se") * 1.96 + enquo("mean_{{var}}")) #Think I need to unquote for this line so it's evaluated
}
test_func(meals)
#Desired output
test_func <- function(var) {
apistrat %>% mutate(col.grad=as.factor(col.grad)) %>% group_by(col.grad) %>%
summarise("mean_{{var}}" := survey_mean({{ var }}, na.rm=TRUE))
}
test_func(meals) %>% mutate(ub_mean_meals=mean_meals_se*1.96+mean_meals) #Want this part in the function
The challenge is wanting to manipulate variable names, which is best done with string arithmetic instead of expression arithmetic. One approach is to create a wrapper that converts symbols to strings, splices them together and then converts the result back to a symbol:
library( tidyverse )
lbl <- function(...) {ensyms(...) %>% reduce(str_c) %>% sym}
You can then use this wrapper to create new labels on the fly:
test_func <- function(var) {
L1 <- lbl( mean_, {{var}} )
L2 <- lbl( mean_, {{var}}, `_se` )
L3 <- lbl( ub_mean_, {{var}} )
apistrat %>% mutate(col.grad=as.factor(col.grad)) %>% group_by(col.grad) %>%
summarise( !!L1 := survey_mean({{ var }}, na.rm=TRUE)) %>%
mutate( !!L3 := !!L2 * 1.96 + !!L1 )
}
test_func(meals)
# # A tibble: 48 x 4
# col.grad mean_meals mean_meals_se ub_mean_meals
# <fct> <dbl> <dbl> <dbl>
# 1 0 51.5 7.71 66.6
# 2 2 96 0.916 97.8
# 3 3 83.9 6.45 96.6
# 4 4 96 2.77 101.
# ...