2016-12-27 147 views
0

我期待打造一个集箱线图,我创建了在打击sampledf2单变量sampledf1每个变量bloxplot的创建数据框的[R箱图。与另一个变量

实际使用情况我已经创建了一组与K均值聚类,现在希望看到自己的每一个与我使用集群数据框的每个变量的发现集群分布。

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将是巨大的,但我没有看到任何功能,我可以链接在一起做到这一点。

回答

1

library(purrr)walk工作很好,当你开始尝试传递这样的公式。 walk()作品像sapply,遍历对象中的元素,只是更灵活的语法。 .引用来自names(sampledf1)的迭代元素。

这将努力获取每个被列在sampledf1命名面板它代表:

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

enter image description here

+0

感谢弥敦道,反正是有,所以我知道每个箱线图具有数据加标签?或者,如果我要做一个名称(sampledf1),则通过sampledf1中的变量顺序? – Jazzmine

+0

你态度处理的顺序是正确的。你真的不需要'map'在这里,但它与不同的输出相同的功能,每一个有用取决于场景。我将在标签的版本编辑 – Nate

3

下面是使用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]) 
     ) 

enter image description here

2

您可以使用ggplot和面,如果你先重塑你的数据为长格式

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)) 

enter image description here

+0

感谢分享这个,因为它的好,有解决问题的方法不止一种,我的学习曲线。 – Jazzmine

0

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) 

enter image description here

相关问题