如何为满足条件的某些组绘制 R 中的图形?
How to plot graphs in R for certain groups that satisfy a criteria?
这是我制作的一个简单数据集:
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)
)
看看每组有多少人:
> table(test$group)
1 2 3 4
2 1 6 1
然后我做了一个箱线图
boxplot(test$height~test$group)
如您所见,第 2 组和第 4 组只有一个人。我想在绘制箱线图时排除他们。换句话说,该图是否针对具有多个观察值的组?
我知道子集函数,认为这可能有用,但不确定在这种情况下如何最好地应用它。
您可以使用 transform()
和 ave()
添加一个列来指示每个组中有多少个观察值,然后使用 subset()
参数仅保留具有超过 1 个观察值的那些.例如
boxplot(height~group,
transform(test, groupcount=ave(ID, group, FUN=length)),
subset=groupcount>1)
注意使用公式语法时只能使用boxplot()
的subset=
参数
你可以这样做:
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)
我喜欢 dplyr 这类东西
library(dplyr)
test %>% group_by(group) %>%
filter(n() > 1) %>%
boxplot(height~group, .)
这是我制作的一个简单数据集:
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)
)
看看每组有多少人:
> table(test$group)
1 2 3 4
2 1 6 1
然后我做了一个箱线图
boxplot(test$height~test$group)
如您所见,第 2 组和第 4 组只有一个人。我想在绘制箱线图时排除他们。换句话说,该图是否针对具有多个观察值的组?
我知道子集函数,认为这可能有用,但不确定在这种情况下如何最好地应用它。
您可以使用 transform()
和 ave()
添加一个列来指示每个组中有多少个观察值,然后使用 subset()
参数仅保留具有超过 1 个观察值的那些.例如
boxplot(height~group,
transform(test, groupcount=ave(ID, group, FUN=length)),
subset=groupcount>1)
注意使用公式语法时只能使用boxplot()
的subset=
参数
你可以这样做:
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)
我喜欢 dplyr 这类东西
library(dplyr)
test %>% group_by(group) %>%
filter(n() > 1) %>%
boxplot(height~group, .)