对多个文件进行相同的计算

时间:2013-07-27 13:05:05

标签: r xts zoo

我有不同名称的不同csv文件。我想进行一些计算,之后我想将结果保存到一个csv文件中。

我的两个csv文件的数据具有以下格式:

文件1:

 day                 price
 2000-12-01 00:00:00 2 
 2000-12-01 06:00:00 3 
 2000-12-01 12:00:00 NA 
 2000-12-01 18:00:00 3 

文件2:

 day                 price
 2000-12-01 00:00:00 12 
 2000-12-01 06:00:00 NA 
 2000-12-01 12:00:00 14 
 2000-12-01 18:00:00 13 

要阅读我使用的文件:

file1 <- read.csv(path_for_file1, header=TRUE, sep=",")
file2 <- read.csv(path_for_file2, header=TRUE, sep=",")

计算过程的一个例子:

library(xts)
file1 <- na.locf(file1)
file2 <- na.locf(file2)

并将结果保存到csv中,其中csv文件的时间戳相同:

merg <- merge(x = file1, y = file2, by = "day", all = TRUE)
write.csv(merge,file='path.csv', row.names=FALSE)

要阅读我尝试this的多个文件。任何想法如何使2个文件的过程成为n个文件?

1 个答案:

答案 0 :(得分:3)

您说您的数据以逗号分隔,但您将其显示为以空格分隔。我将假设您的数据真正以逗号分隔。

不是将它们读入单独的对象,而是将它们读入列表更容易。使用read.zoo而不是read.csv也更容易,因为使用xts / zoo对象合并时间序列要容易得多。

# get list of all files (change pattern to match your actual filenames)
files <- list.files(pattern="file.*csv")
# loop over each file name and read data into an xts object
xtsList <- lapply(files, function(f) {
  d <- as.xts(read.zoo(f, sep=",", header=TRUE, FUN=as.POSIXct))
  d <- align.time(d, 15*60)
  ep <- endpoints(d, "minutes", 15)
  period.apply(d, ep, mean)
})
# set the list names to the file names
names(xtsList) <- files
# merge all the file data into one object, filling in NA with na.locf
x <- do.call(merge, c(xtsList, fill=na.locf))
# write out merged data
write.zoo(x, "path.csv", sep=",")