gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:47:59 24 4
gpt4 key购买 nike

我有不同名称的不同 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 个文件?

最佳答案

您说您的数据以逗号分隔,但您将它们显示为空格分隔。我将假设您的数据确实是用逗号分隔的。

与将它们读入单独的对象相比,将它们读入列表更容易。也更容易使用 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=",")

关于r - 对多个文件进行相同的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17898120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com