首页 > 解决方案 > 如何从写入一个输出文件的多个数据集中获取平均值

问题描述

所以我已经使用 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)

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

标签: rloopsastronomy

解决方案


尝试:

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)
  }

推荐阅读