自从我发布了对 this question 的回答以来,这一直困扰着我。昨天。
考虑以下数据:
carpaint <- data.frame(paint = c(rep(c("blue", "black", "red"),
times=3)),
car1 = c(100, 138, 123, 143, 112,
144, 343, 112, 334),
car2 = c(111, 238, 323, 541, 328,
363, 411, 238, 313),
car3 = c(432, 123, 322, 342, 323,
522, 334, 311, 452))
如果我想按颜色生成箱线图(忽略按“汽车”进行的二次分组),我可以轻松使用 bwplot
中的公式符号来自lattice
.
library(lattice)
bwplot(car1 + car2 + car3 ~ paint, data=carpaint)
但是,要使用 boxplot
获得类似的图来自graphics
,公式表示法不同,所以我必须先将数据转换为长格式然后绘图,如下所示:
carpaint.l = reshape(carpaint, direction="long", varying=2:4, sep="")
boxplot(car ~ paint, data=carpaint.l)
问题:有没有办法获得与 boxplot
相同的情节来自graphics
不首先 reshape 数据,最好使用公式符号? (这忽略了这样一个事实,即这甚至可能不是链接问题的OP想要的输出类型——他们仍然没有对我的答案或@RomanLuštrik的问题发表评论。我只是想满足我的要求好奇心并学习更好地理解公式符号。)
block 引用>Note: providing alternatives is definitely welcome, but I'm hoping that any answers also help me understand why some options are working and others are not. For instance, why does
boxplot(as.matrix(carpaint[, 2:4]) ~ carpaint$paint)
work butboxplot(carpaint[, 2:4] ~ carpaint$paint)
does not. I find that strange because the documentation forboxplot
has examples where they convert matrices to data frames before plotting even though it does not seem to be necessary.
最佳答案
carpaint[, 2:4]
是一个列表,而 cbind(car1, car2, car3)
和 as.matrix(carpaint[, 2 :4])
有一个底层的原子向量表示。箱线图的帮助页面表示“y”参数必须是数字向量。 boxplot.formula
使用 split
:boxplot(split(mf[[response]], mf[-response]), ...)
。 grp
参数被 split
回收以匹配响应向量的长度。 split
无法使用 list/data.frame 形式的三个向量来做到这一点。
关于r - 箱线图(图形)与 bwplot(格子)中的公式表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521041/