如何在函数内添加函数? [英] How to add a function within a function?
问题描述
我具有创建绘图的功能。但是,我想在函数中进行一些预处理,以使用 sjlabelled
包将值转换为标签。
I have a function to create a plot. However, I would like to include some preprocessing within the function to convert values to labels using the sjlabelled
package.
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个变量:var
I'm getting a plot but it is incorrect and I get this error in the console 1 variables were not found in the dataset: var
我尝试使用 curly-curly
, eval
, !!
, sym
, ensym
,但没有一个起作用。
I tried using curly-curly
, eval
, !!
, sym
, ensym
, but none of them worked.
问题在于此行: as_label (var)%>%
推荐答案
问题是 as_label
函数使用删除并替换您可以自己查看该函数: sjlabelled ::: as_label.data.frame
或调用它
The issue is that the as_label
function captures user input with deparse and substitute You can take a look at the function yourself: sjlabelled:::as_label.data.frame
, or call it with debug
.
要解决此问题,可以结合使用 do.call
和 ensym
( enexpr
也可以)。
To get around this, you can use a combination of do.call
and ensym
(enexpr
also works).
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)
这篇关于如何在函数内添加函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!