您好,我在 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).
但我无法让它在一个函数中工作。它没有认识到我对 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).
最佳答案
我们可以在这里使用 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)
-输出
关于r - 如何在 R 中引用图中的变量标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68582982/