2

我正在尝试添加变量名称(即 x、y 和 z)作为每个箱线图的标题:

   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通话中遗漏了一些东西(向 agstudy 寻求以前的帮助)。

4

1 回答 1

5

您当前方法的问题是,在遍历列(data.frame/list 项)时,列名本身会丢失,如下所示

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)
})
于 2013-06-25T01:47:34.560 回答