r - 试图在 R 中“循环”一个函数
问题描述
可能是一个愚蠢的问题,但我目前有一个包含不同物种信息的数据集。现在我需要创建一个只包含特定信息的新数据集(查看下面的代码),有没有办法可以“循环”这个而不是复制和粘贴此代码 20 次并更改物种过滤器?
data_abundance_GL <- TSVPlast %>%
filter(species == "GL") %>% # filter to select the species of interest
group_by(method, observer) %>%
summarise(abundance = length(species))
编辑:
问的原因是我需要根据 3 种不同的方法绘制每个物种的丰度,包括从每个观察者那里计算出的数量。我已经使用
ggplot(data = data_abundance_GL, aes(x = method, y = abundance))+ geom_boxplot(alpha = 0.35, fill = c("orange3", "royalblue", "seagreen3"))+
geom_jitter(aes(shape = observer), size = 4, width = 0.3, height = 0, col = "black")+
scale_shape_manual(values = 1:length(data_abundance_GL$observer))+
labs(shape = "Observer group", fill = "Method", x = "\nMethod", y = "Relative abundance\n", title = "2.4a")+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"),
axis.title = element_text(size = 18),
axis.text = element_text(size = 16, colour = "black"),
strip.background = element_blank(),
legend.text = element_text(size = 14),
legend.title = element_text(size = 16),
title = element_text(size = 30),
strip.text.x = element_blank())
解决方案
你可以做这样的事情
for (specie in unique(TSVPlast$species)) {
TSVPlast %>%
filter(species == specie) %>% # filter to select the species of interest
group_by(method, observer) %>%
summarise(abundance = length(species)) %>%
print()
TSVPlast %>%
filter(species == specie) %>% # filter to select the species of interest
ggplot(aes(x = method, y = abundance)) +
geom_boxplot(alpha = 0.35, fill = c("orange3", "royalblue", "seagreen3"))
# ggsave(str_c(specie, ".pdf))
}
推荐阅读
- java - 在绘制路径中使用箭头键移动图形对象
- docker - 启动时无法跳转到 nginx docker 容器
- python - 不明确地访问 SQLAlchemy 类字段并修复“对象不可下标”错误
- c# - 如何在 SQL Server 中存储以任何编程语言编写的代码/程序
- css - 关键/延迟 CSS 实现
- java - 连接到 sqlite 后我无法执行操作。它立即断开连接
- python - Concat数据帧行明智并合并行(如果存在)
- html - 我的徽标不会出现在标题上,正确的文件路径是什么?
- python - 如何使用增量跳过打印一张两张表
- mysql - MySQL - 如果其中一个包含值,则更新一系列分组行(即使只有一个有库存,也将所有产品设置为有效)