简体   繁体   中英

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

在此处输入图片说明 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).

在此处输入图片说明 Please help!! I also wouldn't mind if someone has a workaround as long as I can put it in the function.

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

在此处输入图片说明

Thing's get a bit messy when trying to use {{}} . You can do

foo <- function(df, var1, var2) {
  title <- eval(rlang::quo_squash(expr(paste(get_label(df, {{var2}}), "by", get_label(df, {{var1}})))))
  df %>% ggplot() + geom_col(aes({{var1}}, {{var2}})) + 
    labs(
      title = title
    )
}

but really the {{}} is a short cut for grabbing the symbols and then injecting it into the expression. It's easier in this case if you do both of those steps separately

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM