如何在函数中添加函数?

How to add a function within a function?

我有一个创建情节的功能。但是,我想在函数中包含一些预处理,以使用 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-curlyeval!!symensym,但其中 none 有效。

这一行有问题:as_label(var) %>%

问题是 as_label 函数使用 deparse and substitute 捕获用户输入 您可以自己查看该函数:sjlabelled:::as_label.data.frame,或使用 debug 调用它.

要解决这个问题,您可以结合使用 do.callensymenexpr 也可以)。

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)