我正在尝试添加变量名称(即x,y和z)作为每个boxplot的标题:
bpdf = data.frame(group=c("A","A","A","B","B","B","C","C","C"),
x=c(1,1,2,2,3,3,3,4,4),
y=c(7,5,2,9,7,6,3,1,2),
z=c(4,5,2,9,8,9,7,6,7))
par(mfrow=c(1,3))
lapply(bpdf[-1],function(x){
y <- sort(tapply(x,bpdf$group,median),decreasing=TRUE)
boxplot(x~factor(bpdf$group,levels=names(y)),
main=paste(colnames(bpdf[-1])))
})
我在main
电话中遗漏了某些内容(ht to agstudy for previous help)。
答案 0 :(得分:5)
当前方法的问题在于,当循环遍历列(data.frame / list items)时,列名称本身会丢失,如
所示devnull <- lapply(bpdf[-1], print)
# [1] 1 1 2 2 3 3 3 4 4
# [1] 7 5 2 9 7 6 3 1 2
# [1] 4 5 2 9 8 9 7 6 7
因此,不是循环遍历列,而是循环遍历变量名称:
par(mfrow = c(1, ncol(bpdf) - 1)
lapply(names(bpdf)[-1], function(var){
x <- bpdf[[var]]
y <- sort(tapply(x, bpdf$group, median), decreasing = TRUE)
boxplot(x ~ factor(bpdf$group,levels=names(y)), main = var)
})