我正在嘗試創建一個允許用戶傳入列名的函式,我發現結果圖只是螢屏中間的一個點。需要進行哪些更改才能使其按預期作業?我的極簡示例是:
library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
`High Temperature` = seq(30, 22, -2), check.names = FALSE)
xVariable <- "Month"
yVariable <- "High Temperature"
yVariable <- enquo(yVariable)
ggplot(weather, aes(x = xVariable, y = !!yVariable)) geom_point()
uj5u.com熱心網友回復:
因為它是參考文本,而不是enquo,使用rlang::sym
xVariable <- "Month"
yVariable <- "High Temperature"
fun <- function(dat, xvar, yvar) {
xvar <- rlang::sym(xvar)
yvar <- rlang::sym(yvar)
p1 <-dat %>%
ggplot(aes(x = !!xvar, y = !!yvar))
geom_point()
return(p1)
}
fun(weather, xVariable, yVariable)

uj5u.com熱心網友回復:
您可以使用aes_string代替aes.
library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
`High Temperature` = seq(30, 22, -2), check.names = FALSE)
xVariable <- "Month"
yVariable <- "`High Temperature`"
ggplot(weather, aes_string(x = xVariable, y = yVariable)) geom_point()

uj5u.com熱心網友回復:
請注意,enquo()是只對功能引數。
如果您將列名作為字串,請使用.data代詞:
fn <- function(data, x, y) {
data %>%
ggplot(aes(x = .data[[x]], y = .data[[y]]))
geom_point()
}
x <- "disp"
y <- "drat"
fn(mtcars, x, y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335789.html
