我具有创建绘图的功能。但是,我想在函数中进行一些预处理,以便使用sjlabelled
包将值转换为标签。
library(haven)
data <- read_spss("http://staff.bath.ac.uk/pssiw/stats2/SAQ.sav")
library(dplyr)
library(labelled)
library(sjlabelled)
bar_plot <- function(data, var) {
data %>%
as_label(var) %>%
filter({{var}} != "Neither") %>%
ggplot(aes({{var}})) +
geom_bar() +
coord_flip() +
theme_classic() +
labs(x = NULL, y = "Count", title = var_label(pull(data, {{var}})))
}
bar_plot(data, Q01)
我正在获取一个图,但是它是不正确的,并且在控制台1 variables were not found in the dataset: var
中出现了此错误
我尝试使用curly-curly
,eval
,!!
,sym
,ensym
,但没有一个起作用。
问题出在此行:as_label(var) %>%
答案 0 :(得分:2)
问题是as_label
函数使用deparse and substitute捕获用户输入。您可以自己查看一下该函数:sjlabelled:::as_label.data.frame
,或使用debug
进行调用。 / p>
要解决此问题,可以结合使用do.call
和ensym
(enexpr
也可以)。
bar_plot <- function(data, var) {
data <- do.call(as_label, list(data, ensym(var)))
data %>%
filter({{ var }} != "Neither") %>%
ggplot(aes({{ var }})) +
geom_bar() +
coord_flip() +
theme_classic() +
labs(x = NULL, y = "Count", title = var_label(pull(data, {{ var }})))
}
data %>% bar_plot(Q01)