【问题标题】:How to get averages of values from multiple data sets written to one output file如何从写入一个输出文件的多个数据集中获取平均值
【发布时间】:2021-07-26 15:48:27
【问题描述】:

所以我已经使用 R 几年了,但我发现思考编码问题仍然非常困难,所以如果有任何解释可以尽可能少地假设,我真的很感激!

基本上,我有很多数据文件对应不同的日期。我想编写某种循环,我可以在其中读取每天的数据文件,进行分析(例如,其中一列的平均值),然后输出到一个单独的文件,该文件由日期/名称标记文件(日期目前不是数据文件的一部分,所以我还没有弄清楚如何在代码中包含它)

为了使事情复杂化,我需要从数据文件中提取子集以单独分析。我已经想出了如何做到这一点并获得单独的方法我只是不知道如何合并循环。

#separating LINK (SL) satellites from entire list
SL<- data[grepl("^LINK", data$name), ]
#separating non-SL sat. from entire list
nonSL<- data[!grepl("^LINK", data$name), ]


analyse<- function(filenames){
  #mean mag. for satellites in data frame
  meansat<- print(mean(data[,2]))
  #mean mag. for LINK sat. in data frame
  meanSLsat<- print(mean(SL[,2]))
  #mean mag. non-SL sat. in data frame
  meannonSLsat<- print(mean(nonSL[,2]))
  means<-c(meansat, meanSLsat, meannonSLsat)
}

#looping in data files
filenames<- list.files(path = "Data")
for (f in filenames) {
  print(f)
  allmeans<-analyse(f)
}

write.table(allmeans, file = "outputloop.txt", col.names = "Mean Magnitude", quote = FALSE, row.names = FALSE)

这是我到目前为止所拥有的,但它不起作用,我不明白为什么。循环的尝试很微弱,但我不知道当我需要分离子类时在哪里/放置循环的顺序,所以任何帮助都将不胜感激!提前谢谢!

【问题讨论】:

    标签: r loops astronomy


    【解决方案1】:

    试试:

    for (f in filenames) {
      allmeans <-analyse(f)
      file_out <- paste(f, "_output.txt", sep='') # This is for creating different filenames for each file analyzed
      write.table(allmeans, file = file_out , col.names = "Mean Magnitude", quote = FALSE, row.names = FALSE)
      }
    

    【讨论】:

    • 感谢您的建议。该更改只是创建了多个输出文件,但它们仍然只有最后分析的数据文件中的值。所以我有两个以输入名称开头的文件,最后是 output.txt。
    • 您可以只负责读取一个文件并在分析函数中使用一个文件名作为参数分析该文件。然后循环将达到您的目的,我认为
    • 对不起,我不确定我明白你的意思,请你介意解释一下吗?
    • 在您的分析功能中,您没有读取任何文件。我的意思是您在分析函数中包含文件读取代码: analyse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多