我試圖制作一個函式來根據分組因子和如下定義的數值快速制作錯誤欄:
#### Function ####
quick.error <- function(data,x,y){
d <- data
plot.d <- d %>%
mutate(x = as.factor(x)) %>%
group_by(x) %>%
summarise(
sd = sd(y, na.rm = TRUE),
mean = mean(y, na.rm=TRUE)
) %>%
ggplot(aes(x,
mean,
fill=x))
geom_col(color = "black")
geom_errorbar(aes(ymin = mean-sd,
ymax = mean sd),
width = 0.2)
theme(legend.position = "none")
return(plot.d)
}
但是,當我嘗試使用iris資料集運行它時:
#### Test ####
quick.error(data=iris,
x=Species,
y=Petal.Length)
這給了我一個錯誤:
Error in `mutate()`:
! Problem while computing `x = as.factor(x)`.
Caused by error in `is.factor()`:
! object 'Species' not found
使用運算子顯式運行它$會給我一個不同的問題:
#### Test ####
quick.error(data=iris,
x=iris$Species,
y=iris$Petal.Length)
正如您在此處看到的,它使所有條形圖都相同,我假設是因為它沒有像預期的那樣對平均值進行分組:

我該如何解決這個問題?
uj5u.com熱心網友回復:
正如我在評論中指出的,這是一個典型的非標準評估問題。這是一個修改后的功能,我相信它可以滿足您的需求。
quick.error <- function(data,x,y){
d <- data
plot.d <- d %>%
mutate({{ x }} := as.factor({{ x }})) %>%
group_by({{ x }}) %>%
summarise(
sd = sd({{ y }}, na.rm = TRUE),
mean = mean({{ y }}, na.rm=TRUE)
) %>%
ggplot(aes({{ x }},
mean,
fill={{ x }}))
geom_col(color = "black")
geom_errorbar(aes(ymin = mean-sd,
ymax = mean sd),
width = 0.2)
theme(legend.position = "none")
return(plot.d)
}
quick.error(data=iris,
x=Species,
y=Petal.Length)

uj5u.com熱心網友回復:
將不帶引號的列名傳遞給函式
... 需要使用包含運算子 {{ 或者在更復雜的情況下使用注入運算子 !! 進行注入。
有關更多資訊,請參見例如這個小插圖。
因此,您可以通過將函式包裝在函式內部x來使函式作業:y{{
quick.error <- function(data, x, y) {
d <- data
plot.d <- d %>%
mutate(x = as.factor({{ x }})) %>%
group_by(x) %>%
summarise(
sd = sd({{ y }}, na.rm = TRUE),
mean = mean({{ y }}, na.rm = TRUE)
) %>%
ggplot(aes(x,
mean,
fill = x
))
geom_col(color = "black")
geom_errorbar(aes(
ymin = mean - sd,
ymax = mean sd
),
width = 0.2
)
theme(legend.position = "none")
return(plot.d)
}
library(ggplot2)
library(dplyr)
quick.error(
data = iris,
x = Species,
y = Petal.Length
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519558.html
上一篇:替換熊貓資料框列中的字串
