I am trying to add the variable name (ie, x, y, and z) as the title for each 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])))
})
I am missing something in the main
call (ht to agstudy for previous help).
The problem with your current approach is that, when looping over the columns (data.frame/list items), the column names themselves are lost, as shown by
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
So instead of looping over the columns, you could loop over the variable names:
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)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.