【问题标题】:How to add a function within a function?如何在函数中添加函数?
【发布时间】:2020-09-11 17:14:22
【问题描述】:

我有一个创建情节的功能。但是,我想在函数中包含一些预处理,以使用 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,但它们都不起作用。

问题出在这一行:as_label(var) %&gt;%

【问题讨论】:

    标签: r dplyr nse


    【解决方案1】:

    问题在于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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-06
      • 2011-08-08
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多