在for循环中分配多个变量

时间:2019-09-22 20:23:28

标签: r variables

我有一段重复7次的代码,我正在尝试压缩代码。我正在尝试运行一个函数,并且raw_data_*文件是数据帧。这就是我想要实现的(未压缩的代码):

tax_1 <- count_taxa(raw_data_1, "Site_1", "Domain", domain_n)
tax_2 <- count_taxa(raw_data_2, "Site_2", "Domain", domain_n)
tax_3 <- count_taxa(raw_data_3, "Site_3", "Domain", domain_n)
tax_4 <- count_taxa(raw_data_4, "Site_4", "Domain", domain_n)
tax_5 <- count_taxa(raw_data_5, "Site_5", "Domain", domain_n)
tax_6 <- count_taxa(raw_data_6, "Site_6", "Domain", domain_n)
tax_7 <- count_taxa(raw_data_7, "Site_7", "Domain", domain_n)
all_tax <- bind_rows(tax_1, tax_2, tax_3, tax_4, tax_5, tax_6, tax_7)

我正在尝试做这样的事情:

tax_list <- list(raw_data_1, raw_data_2, raw_data_3, raw_data_4, raw_data_5, raw_data_6, raw_data_7)
site_list <- list("Site_1", "Site_2", "Site_3", "Site_4", "Site_5", "Site_6", "Site_7")

for (tax in tax_list) {

  tax_1 <- count_taxa(tax, site, domain_n)
????

}
all_tax <- bind_rows(tax_1, tax_2, tax_3, tax_4, tax_5, tax_6, tax_7)

但是我不知道这是否有可能。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以创建一个空列表,然后在循环进行时向其添加数据帧。最后,您可以使用all_tax将它们全部绑定到Reduce中。

tax_list <- list(raw_data_1, raw_data_2, raw_data_3, raw_data_4, raw_data_5, raw_data_6, raw_data_7)
site_list <- list("Site_1", "Site_2", "Site_3", "Site_4", "Site_5", "Site_6", "Site_7")

proc_df <- list()

for (i in seq_along(tax_list)) {
  proc_df <- c(proc_df, count_taxa(tax_list[[i]], site_list[[i]], domain_n))
}

all_tax <- Reduce(rbind, proc_df)

一种替代方法是使用map2_dfr中的purrr函数:

purrr::map2_dfr(tax_list, site_list, count_taxa, domain_n)