简体   繁体   English

如何在满足标准的某些群体中绘制R图?

[英]How to plot graphs in R for certain groups that satisfy a criteria?

Here's a simple dataset I made: 这是我制作的一个简单数据集:

test <- data.frame(
   ID=1:10,
   group=c(3,2,1,3,3,3,4,1,3,3),
   height=c(156,167,165,187,153,172,178,191,155,189)
)

And a look at the how many individuals are in each group: 看看每组中有多少人:

> table(test$group)
1 2 3 4 
2 1 6 1 

Then I did a boxplot 然后我做了一个箱形图

boxplot(test$height~test$group)

boxplot按组高度

As you can see group 2 and group 4 only have one individual in them.. I want to exclude them when doing the boxplot. 正如你所看到的那样,第2组和第4组中只有一个人。我想在制作盒子图时将它们排除在外。 In other words, do the plot on groups that have more than one observation? 换句话说,对具有多个观察的群体进行绘图?

I know the subset function, and think this might be useful, but not sure how to best apply it in this case. 我知道子集函数,并认为这可能有用,但不确定如何在这种情况下最好地应用它。

You can use transform() and ave() to add a column indicating how many observations are in each group and then use the subset() parameter to only keep those with more than 1 obs. 您可以使用transform()ave()添加一个列,指示每个组中有多少观察,然后使用subset()参数仅保留多于1个obs的那些。 For example 例如

boxplot(height~group, 
    transform(test, groupcount=ave(ID, group, FUN=length)), 
    subset=groupcount>1)

在此输入图像描述

Note that you can only use the subset= parameter of boxplot() when you use the formula syntax. 请注意,在使用公式语法时,只能使用boxplot()subset=参数。

I like dplyr for these sorts of things 我喜欢dplyr这些东西

library(dplyr)
test %>% group_by(group) %>%
         filter(n() > 1) %>% 
         boxplot(height~group, .) 

You can do this: 你可以这样做:

tab <- as.data.frame(table(test$group))
tab1 <- tab[which(tab$Freq > 1),]
test2 <- test[which(test$group %in% tab1$Var1),]
boxplot(test2$height~test2$group)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM