Search code examples
rdplyrnse

How to add a function within a function?


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)

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

I tried using curly-curly, eval, !!, sym, ensym, but none of them worked.

The problem is with this line: as_label(var) %>%


Solution

  • 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.

    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)