我正在做一些簡單的事情,但 tidyeval 總是讓我感到困惑。在這種情況下,我有一個繪制一些東西的函式,我還想在之后使用我正在繪制的列的名稱保存它,如下所示:
bar_plot= function(table, col_plot){
ggplot(table, aes(x=region,
y= {{col_plot}}))
geom_bar(stat = "identity", fill="steelblue")
ggsave(glue('results/{col_plot}.png'))
}
情節沒有問題,但我無法保存它(找不到物件,因為它沒有將其作為字串讀取)。嘗試使用quo, enquo, sym,但沒有任何效果。將我的變數名轉換為函式內的字串的方法是什么?
為了重現性,這就足夠了:
df = data.frame(region = c(1, 2), mean_age = c(20, 30))
謝謝 !
uj5u.com熱心網友回復:
你可以這樣做:
bar_plot <- function(table, col_plot) {
p <- ggplot(table, aes(region, {{col_plot}})) geom_col(fill = "steelblue")
ggsave(paste0('results/', deparse(substitute(col_plot)), '.png'), p)
}
bar_plot(df, mean_age)
所以你有了:
./results/mean_age.png

uj5u.com熱心網友回復:
把繪圖部分抽象出來,重點放在檔案名上,我想你也可以用rlang::as_name這里把符號轉換成你需要的字串。
library(ggplot2)
df <- data.frame(region = c(1, 2), mean_age = c(20, 30))
bar_plot <- function(table, col_plot) {
# ggplot(table, aes(
# x = region,
# y = {{ col_plot }}
# ))
# geom_bar(stat = "identity", fill = "steelblue")
filename <- glue::glue("results/{rlang::as_name(enquo(col_plot))}.png")
filename
}
bar_plot(df, mean_age)
#> results/mean_age.png
請注意,我們需要做兩件事:首先將引數包裝在col_plot中enquo,因此我們得到mean_age的是 of 而不是字面意思col_plot。然后as_name()轉換mean_age成"mean-age".
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444185.html
上一篇:執行緒成員為空,但已保存
