r - 如何在 R 中引用图中的变量标签?

标签 r tidyverse rlang tidyeval r-haven

您好,我在 R 中将带标签的数据与 haven 和 sjlabelled 包一起使用。我想在绘制它时引用变量的标签。如果我直接引用数据框和标签(请参阅图表标题中的 get_label 函数),它就会起作用。

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 但我无法让它在一个函数中工作。它没有认识到我对 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 请帮忙!!我也不介意是否有人有解决方法,只要我可以将其放入函数中即可。

最佳答案

我们可以在这里使用 ensym 而不是 {{}}

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]]))
  )
  
  
}

-测试

efc %>% 
    foo(c161sex, c12hour)

-输出

enter image description here

关于r - 如何在 R 中引用图中的变量标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68582982/

相关文章:

r - magrittr `.` 代词和 rlang `.data` 代词是相同的,但这怎么可能呢?

R将一长串问卷选择转换为每个问卷一行的数据框

r - 如何仅从路径提取文件/文件夹名?

R ggplot2 和 gganimate : animation changes at end

r - 基于 R 中的其他列创建列序列

r - dplyr 的多重滞后

r - 如何在带有 tidyr 和 ggplot2 的函数中使用 dplyr 的 enquo 和 quo_name

r - 二分图匹配以匹配两个集合

r - 模糊连接与 R 中的部分字符串匹配

r - Tidyverse 按行绑定(bind)未命名向量列表的方法 - do.call(rbind,x) 等效