【问题标题】:Bind iterations of a loop as rows in a data.frame for each i将循环的迭代绑定为 data.frame 中每个 i 的行
【发布时间】:2020-11-05 05:03:18
【问题描述】:

我有这个dplyr 管道在一个工作正常的循环中(print() 只是为了让我在处理它时可以看到我在做什么):

for (species in species_vector) {
  for (month in month_vector) {
    print(
      data_fish %>%
        filter(Species == species,
               Month == month,
               Lt %in% some_vector%>%
        group_by(Month) %>%
        summarise(Mean_Lt = mean(Lt),
                  StDev_Lt = sd(Lt),
                  Count = sum(Count))%>%
        as.data.frame()%>%
        
    )
  }
}

每次迭代都会为每个物种的每个月生成不同的data.frame。这是一个物种一个月(3 或 3 月)结果的一个例子:

Month  Mean_Lt  StDev_Lt Count
3      4.3303   0.7742   221

我的问题是:我想rbind() 在单独的dfs 中属于每个物种的所有月份。以每个物种的 df 结尾,每个 df 包含有关该物种的所有月份。

【问题讨论】:

  • purrr::map_dfr,这就是你需要的link

标签: r dataframe for-loop dplyr


【解决方案1】:

这是使用列表的一般方法:


output_list = list()

for(species in species_vector){
  species_df = data.frame(stringsAsFactors = FALSE)
  for(month in month_vector){
    # build result_for_month
    # ...
    species_df = rbind(species_df, result_for_month)
  }
  output_list[species] <- species_df
}

然后您可以使用以下方式访问您的输出:

output_list[["my_species"]]

【讨论】:

    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 2020-07-06
    • 2017-04-28
    • 2017-04-26
    • 2016-01-18
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多