r - For 循环为数据框中的所有唯一值创建直方图
问题描述
我有 18 个不同的物种,它们的大小等级和每个大小等级的观察计数。我正在尝试创建一个 for 循环,该循环将为每个物种创建一个单独的直方图(不是方面,因为有太多物种)。For 循环是我在 R 中最薄弱的领域,我经常做更多的代码来避免它们,但有 18 个物种不再是一种选择。
这是我的格式化数据示例:
Species Size.Class TotalCount
P. porphyreus 35 1
P. porphyreus 20 5
P. porphyreus 25 5
P. insularis 35 2
P. insularis 5 10
P. insularis 10 10
P. insularis 30 12
P. insularis 25 35
P. insularis 15 36
P. insularis 20 36
P. cyclostomus 30 2
P. cyclostomus 35 2
P. cyclostomus 25 4
P. cyclostomus 15 7
P. cyclostomus 20 8
当我为一个物种创建直方图时,我得到了预期的结果:
ggplot(subset(Spcount,Species %in% c("P. porphyreus")),aes(x=Size.Class))+
geom_histogram(binwidth=5)+
ggtitle("P. porphyreus Histogram")+
labs(y= "Total Count", x = "Size Class")
但是当我尝试使用这个 for 循环自动化它时:
FOR (i in Spcount$Species) {
ggplot(subset(Spcount,Species %in% c("i")),aes(x=Size.Class))+
geom_histogram(binwidth=5)+
ggtitle("i Histogram")+
labs(y= "Total Count", x = "Size Class")
}
我得到一个标题为“i Histogram”的图表,但它是空白的,没有错误或警告。
解决方案
您应该对 Species 的唯一值进行子集化,通过for (i in unique(Spcount$Species))
首先,我制作您的示例数据:
Spcount <- data.frame(
Species = c(
"P. porphyreus", "P. porphyreus", "P. porphyreus",
"P. insularis", "P. insularis", "P. insularis", "P. insularis",
"P. insularis", "P. insularis", "P. insularis", "P. cyclostomus",
"P. cyclostomus", "P. cyclostomus", "P. cyclostomus", "P. cyclostomus"
),
Size.Class = c(
35, 20, 25, 35, 5, 10, 30, 25, 15, 20, 30, 35, 25, 15, 20
),
TotalCount = c(
1, 5, 5, 2, 10, 10, 12, 35, 36, 36, 2, 2, 4, 7, 8
)
)
然后,
subseted_Spcount = 0
plot = 0
for (i in unique(Spcount$Species)) {
subseted_Spcount = subset(Spcount, Species == i)
plot <- ggplot(subseted_Spcount, aes(x = Size.Class)) +
geom_histogram(binwidth = 5) +
ggtitle(paste0(i, " Histogram")) +
labs(y= "Total Count", x = "Size Class")
print(plot)
}
不要忘记使用Next plot (Ctrl + Alt + F12)
和Previous plot (Ctrl + Alt + F11)
查看不同的直方图。
推荐阅读
- r - 将数据帧写入R中的dbf文件
- python - 为什么 PyQt 中的这段代码允许我不选中所有单选按钮?
- .htaccess - htaccess RewriteRules 不适用于子目录
- python-3.x - Python 检查类型是否匹配特定类型
- powershell - 如何在不删除已经存在的用户的情况下将用户添加到 powershell 中的共享?
- xcode - Cloudkit 私有数据库未显示
- javascript - Leaflet 的 GeoJSON 格式——某些 GeoJSON 不显示,而另一些则显示
- python - 如何使用构造函数关键字参数指定 Python 类属性
- c++ - 两个文件互相使用功能 - 如何解决?
- python - Pygame.spritecollide() 检测精灵之间的碰撞,即使它们没有接触