使用另一个变量创建数据框的 R 箱线图

Create R boxplots of dataframe with another variable

我想创建一组箱形图,我在其中针对 sampledf2 中的单个变量为 sampledf1 中的每个变量创建了一个 bloxplot。

实际用例是我用 k-means 创建了一组聚类,现在想用我用于聚类的数据框中的每个变量查看每个找到的聚类的分布。

sampledf1 <- as.data.frame(replicate(6, sample(c(1:10,NA))))
sampledf2 <- as.data.frame(replicate(1, sample(c(21:30,NA))))

然后我想看到一个箱形图,其中包含 sampledf1 中的每个变量与 sampledf2 中的唯一变量配对。

我想使用类似的东西:

sapply(boxplot(sampledf1~sampledf2$V1))

但这给了我这个错误:

Error in match.fun(FUN) : argument "FUN" is missing, with no default

无论如何我可以做到这一点 dplyr 会很棒但是我没有看到任何可以链接在一起的函数来做到这一点。

当您开始尝试传递这样的公式时,

library(purrr)walk 效果很好。 walk()sapply 类似,迭代对象中的元素,只是语法更灵活。 . 指的是 names(sampledf1).

中的迭代元素

这将使每个面板按 sampledf1 中它代表的列命名:

library(purrr)    
par(mfrow = c(2,3))
purrr::walk(names(sampledf1), ~boxplot(sampledf1[,.]~sampledf2$V1, main = .))

这是使用 lapplyseq_along 的方法。我们使用 seq_along 遍历 sampledf1 的列。我们可以使用索引 inames 函数提取变量名。

par(mfrow = c(2,3))
lapply(seq_along(sampledf1), 
       FUN  = function(i) 
           boxplot(sampledf1[,i] ~ sampledf2$V1, main = names(sampledf1)[i])
       )

如果您先将数据重塑为长格式,则可以使用 ggplot 和 facets

library(reshape2)
library(ggplot2)
s.all = cbind(sampledf1, f2=sampledf2$V1)
s.long = melt(s.all, id = 'f2')
ggplot(s.long) +
  geom_boxplot(aes(x=f2, group=f2, y=value)) +
  facet_wrap(~variable) +
  scale_x_continuous(breaks=unique(s.long$f2))

ggplot2 变体:

library(reshape2)
library(ggplot2)

sampledf1$X <- sampledf2$V1
ggplot(melt(sampledf1, id.vars="X", na.rm=T), aes(factor(X),value)) + 
  geom_boxplot() + facet_wrap( ~ variable, nrow=2)