rtidyverserlangtidyevalr-haven

How to reference variable label in graph in R?


Hi I am using labelled data in R with the haven and sjlabelled packages. I want to reference the variable's label when I graph it. It works if I directly reference the dataframe and the label (see get_label function in the graph's title).

library(sjlabelled)
library(tidyverse)

data(efc)
efc %>% get_label(c12hour, c161sex)
#>                                    c12hour 
#> "average number of hours of care per week" 
#>                                    c161sex 
#>                           "carer's gender"

efc %>% ggplot() + geom_col(aes(c161sex, c12hour)) + 
  labs(
    title = paste(get_label(efc, c12hour), "by", get_label(efc, c161sex))
  )
#> Warning: Removed 7 rows containing missing values (position_stack).

enter image description here But I can't get it to work within a function. It's not recognizing my poor understanding of tidy eval.

foo <- function(df, var1, var2) {
  {{df}} %>% ggplot() + geom_col(aes({{var1}}, {{var2}})) + 
  labs(
    title = paste(get_label({{df}}, {{var2}}), "by", get_label({{df}}, {{var1}}))
  )
}
efc %>% foo(c161sex, c12hour)
#> 1 variables were not found in the dataset: {
#>     {
#>         var2
#>     }
#> }
#> 1 variables were not found in the dataset: {
#>     {
#>         var1
#>     }
#> }
#> Warning: Removed 7 rows containing missing values (position_stack).

enter image description here Please help!! I also wouldn't mind if someone has a workaround as long as I can put it in the function.


Solution

  • We may use ensym here instead of {{}}

    foo <- function(df, var1, var2) {
     var1 <- rlang::ensym(var1)
     var2 <- rlang::ensym(var2)
      df %>% ggplot() + geom_col(aes(!!var1, !!var2)) + 
      labs(
        title = paste(get_label(df[[var2]]), "by", get_label(df[[var1]]))
      )
      
      
    }
    

    -testing

    efc %>% 
        foo(c161sex, c12hour)
    

    -output

    enter image description here