我的数据框类似于df
。对于每个因素,我想创建一个比较该因子与最终得分的箱线图。没有循环,它看起来像下面的代码。在实践中,我想对40列进行此操作,并将其显示在网格中。在这里,某种循环列似乎是合适的,但我不确定如何做到这一点。
library(ggplot2)
library(gridExtra)
scores <- c(97, 98, 90, 92)
factor1 <- c(1, 0, 0, 1)
factor2 <- c(2, 1, 2, 0)
factor3 <- c(0, 0, 0, 1)
df <- data.frame(scores, factor1, factor2, factor3)
plot1 <- ggplot(df, aes(x=factor(factor1), y=scores)) + geom_boxplot()
plot2 <- ggplot(df, aes(x=factor(factor2), y=scores)) + geom_boxplot()
plot3 <- ggplot(df, aes(x=factor(factor3), y=scores)) + geom_boxplot()
grid.arrange(plot1, plot2, plot3, ncol=2)
答案 0 :(得分:1)
library(ggplot2)
library(gridExtra)
df <- data.frame(scores=c(97, 98, 90, 92), factor1=c(1, 0, 0, 1),
factor2=c(2, 1, 2, 0), factor3=c(0, 0, 0, 1))
fun <- function(x) {
dts <- df[,c("scores",x)]
names(dts)[2] <- "varx"
p <- ggplot(dts, aes(x=factor(varx), y=scores)) + geom_boxplot() + xlab(x)
return(p)
}
ps <- lapply(names(df)[-1], fun)
grid.arrange(grobs=ps, ncol=2)