【问题标题】:Reading Series of CSV Files into R, Running Functions, Writing Outputs to New Files将一系列 CSV 文件读入 R、运行函数、将输出写入新文件
【发布时间】:2019-09-25 20:28:15
【问题描述】:

我正在尝试自动计算一些动物能量需求,其中我输入了喂食天数、每日采食量等。我的代码首先从 CSV 读取初始数据,使用它来计算外部的一些起始值循环,运行当天的能量计算循环,计算饲料时间,将这些结果存储在数据帧中,然后将最终数据帧写入 CSV。

我有来自超过 300 只羊的数据,基于这样的单个记录,并希望自动读取文件,并将结果写入特定文件夹中的单独 CSV 文件。我知道这意味着一个循环中的一个循环,但我试图弄清楚如何去做。

我知道我需要使用 files.list 读取文件,如下所示:

files = list.files("C:/Users/Me/Desktop/Sheepfiles/", pattern = "Sheep+.*csv")

但我希望每个文件都作为其自己的数据框在模型中运行,并且我需要将所有内容分开进出。

setwd("C:Users/....../Sheepfiles")


input =  read.csv(file = "Sheep131.csv", header = TRUE, sep =",")
#set up initialized values outside loop here
LWt0 = input$LWT[1]
EBW = LWT0*.96*.891
#constants go here


Results = NULL;
timefeed = input$DOF

#now the loop
for (i in timefeed) 
{

#differential equations and calculations here

 results1 = (c(t, NEG, MEI, OldMEI, HPmaint, EBW, ID, TRT))
 names(results1) = c("DOF", "NEG", "MEI", "OldMEI","HPmaint", "EBW", "ID", "TRT")

 print((results1))
 Results = rbind(Results,results1)


#update variables to new values here

}
write.csv(Results, file = "Results131.csv")

我想要的是让他们能够拥有名称中带有 SheepX 的文件,每只羊一个,其中 X 是耳标 #,将这些文件读入、计算,然后自动将结果与 ResultsX.csv 一起输出.如果有帮助,耳标编号位于“ID”列下的原始输入文件中。所以对于绵羊 1:150 我会有 Results1:150 等

稍后,我需要能够重新读取这些结果文件,提取特定日期的输出,然后将它们拉入数据框以与观察结果进行比较,但这是我得到所有这些后的下一步文件贯穿模型。

【问题讨论】:

    标签: r loops csv


    【解决方案1】:

    您需要遍历文件名并为每个文件执行现有代码,因此解决方案可能如下所示:

    setwd("C:Users/....../Sheepfiles")
    
    files = list.files("C:/Users/Me/Desktop/Sheepfiles/", pattern = "Sheep+.*csv")
    
    for (i in files) {
      input =  read.csv(file = i,
                        header = TRUE,
                        sep = ",")
      #set up initialized values outside loop here
      LWt0 = input$LWT[1]
      EBW = LWT0 * .96 * .891
      #constants go here
    
    
      Results = NULL
    
      timefeed = input$DOF
    
      #now the loop
      for (i in timefeed)
      {
        #differential equations and calculations here
    
        results1 = (c(t, NEG, MEI, OldMEI, HPmaint, EBW, ID, TRT))
        names(results1) = c("DOF", "NEG", "MEI", "OldMEI", "HPmaint", "EBW", "ID", "TRT")
    
        print((results1))
        Results = rbind(Results, results1)
    
    
        #update variables to new values here
    
      }
    
      # automatically generate filename for results
      result.filename <- gsub("Sheep", "Results", i)
    
      write.csv(Results, file = result.filename)
    }
    

    所以你基本上在你的代码周围包裹了一个 for 循环,你的文件名作为计数器变量。

    【讨论】:

    • 到目前为止,这可以让事情循环并运行,但由于某种原因,输出名称很奇怪?比如,如果我在羊 131、51 和 76 中循环,我会得到名为 243、249 和 259 的输出文件。我不确定这些数字来自哪里?
    • 解决了后一个问题,意识到我在 i 上进行了双索引,这就是输出文件名的来源。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多