[英]lapply with boxplots in R
我正在嘗試使用lapply
在 R 中創建許多箱形圖。 當我使用ggplot
function 創建箱線圖時,我得到了正確的 output。 當我嘗試使用colnames
通過lapply
傳遞框 plot function 時,function 無法按預期工作。 附上正確的 plot 和不正確的 plot 示例。
doPlot = function(var1) {
# Create the plot object
ggobj = ggplot(wdbc_train, aes(x = diagnosis,y=var1)) + geom_boxplot()
# Add some titles and axis labels
ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") +
ylab(var1)
}
lapply(colnames(wdbc_train),doPlot)
正確的
不正確
您需要從命名變量中get
數據。
doPlot = function(var1) {
# Create the plot object
ggobj = ggplot(wdbc_train, aes(x = diagnosis, y=get(var1))) +
geom_boxplot()
# Add some titles and axis labels
ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") + ylab(var1)
}
doPlot = function(var1) {
# Create the plot object
ggobj = ggplot(iris, aes(x = Species, y=get(var1))) + geom_boxplot()
# Add some titles and axis labels
ggobj = ggobj + ggtitle(var1) + xlab("Species") + ylab(var1)
}
p <- lapply(colnames(iris)[-5], doPlot)
library(gridExtra)
grid.arrange(grobs=p)
當您將var1
傳遞給 function doPlot
時,它只是一個字符串。 需要解釋為dataframe的一列。
我們可以使用帶有sym
和!!
的非標准評估 (NSE) 這里。
library(ggplot2)
library(rlang)
doPlot = function(df, var1) {
# Create the plot object
ggobj = ggplot(df, aes(diagnosis,y = !!sym(var1))) + geom_boxplot()
# Add some titles and axis labels
ggobj + ggtitle(var1) + xlab("diagnosis") + ylab(var1)
}
然后將其應用於每一列,這將為您提供list_plot
中的圖列表。
list_plot <- lapply(colnames(wdbc_train), doPlot, df = wdbc_train)
以前,這可以使用aes_string
來實現,其中您可以將列名作為字符串傳遞,但這已被棄用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.