【问题标题】:Call new data frame for each iteration: Loop through data frames?为每次迭代调用新数据框:循环遍历数据框?
【发布时间】:2019-02-25 03:13:20
【问题描述】:

我正在设计一个模拟,它使用来自两个单独数据帧(dfyear)的输入迭代地运行一段代码。生成的数据框是 df 的修改版本,然后以两个单独的文件名保存在我的硬盘驱动器上:一个永久存储以供将来分析,另一个为下一次迭代调用。

这是我的问题:数据框year 必须是每次迭代的全新数据框(即下一年的数据)。

这是否可以通过类似于 for 循环的方式来完成,其中索引 [i] 是下一年的数据框(而不是数据框中的一行,这就是我理解的 for 循环的操作方式)?我怀疑答案涉及列表?以下是一些试图证明该问题的虚拟数据:

df <- tibble(
  x = 1:25,
  y = rnorm(25, 22, 8))

year1990 <- tibble(
  Year = 1990, 
  DayOfYear = 1:6, 
  temp = seq(0, 20, 4))

year1991 <- tibble(
  Year = 1991, 
  DayOfYear = 1:6, 
  temp = seq(0, 25, 5))

year1992 <- tibble(
  Year = 1992, 
  DayOfYear = 1:6, 
  temp = seq(0, 15, 3))

#### Beginning of Code to Be Repeated ####

year <- year1990         # Start with this year, BUT each subsequent iteration needs the following year's data
df$survive <- ifelse(max(year$temp) <= df$y, "Dead", "Live")
write.csv(df, "location/f.csv",row.names=FALSE)  # Write temporary CSV to be recalled
write.csv(df, paste(year[1,1], ".csv", sep = ""), row.names = FALSE)      # Write permanent CSV for storage

#### End of Code to Be Repeated ####

# Reload the newly modified data frame
setwd()
df <- read.csv("df.csv")  

目前,我手动重新加载 df 并为每次迭代重置 year(例如,在此示例中,我将使用 year1991 重新分配 year 用于第二次迭代),但我确信有更好的使整个过程自动化的方法。谢谢!

【问题讨论】:

  • 您在哪里为每次迭代重置年份?我很困惑,因为 df 中没有 year
  • @Parfait,感谢您的提问。 “Beginning...”之后的行,我使用明年的数据分配对象名称year。这有意义吗?

标签: r loops recursion iteration simulation


【解决方案1】:

只需将对象保存在命名列表中(如果它们最初位于具有splitby 的一个数据框中,则可以创建该列表)。然后使用Map(包装到mapply)通过定义的循环过程通过列表的名称和对象逐元素循环

year_list <- list(
  year1990 = tibble(Year = 1990, DayOfYear = 1:6, temp = seq(0, 20, 4)),    
  year1991 = tibble(Year = 1991, DayOfYear = 1:6, temp = seq(0, 25, 5)),    
  year1992 = tibble(Year = 1992, DayOfYear = 1:6, temp = seq(0, 15, 3))
)

proc <- function(n, d) {    
    year <- d        
    df$survive <- ifelse(max(year$temp) <= df$y, "Dead", "Live")
    write.csv(df, "location/f.csv", row.names = FALSE)  

    # Write temporary CSV to be recalled
    write.csv(df, paste0(n, ".csv"), row.names = FALSE)  

    return(df)
}

# ITERATIVELY SAVES CSVs AND RETURNS dfs WITH UPDATED survive COLUMN
output_list <- Map(proc, names(year_list), year_list)

【讨论】:

  • 这确实有效,谢谢!通过使用 do.call("rbind", output_list) 我将列表组合成一个数据框。两个小问题:#1:我对 n 在第二个 write.csv 函数中所做的事情还有些模糊。也许我需要在mapply 上学习。 #2:如何在df 中创建一个新列来存储该迭代的年份?
  • 确实你可以在最后进行行绑定。并且 n 被传递到write.csv 的文件名中。它使用 d 逐元素迭代。只需在write.csv 调用之前为列添加一行:df$year &lt;- n
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多