首页 > 解决方案 > 试图在 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())

标签: r

解决方案


你可以做这样的事情

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

推荐阅读