gpt4 book ai didi

r - 如何按时间间隔匹配数据帧?

转载 作者:行者123 更新时间:2023-12-04 09:30:20 26 4
gpt4 key购买 nike

这是我从数据记录器导入原始数据时经常出现的问题。温度记录器设置为每十分钟记录一次温度,单独的气体记录器设置为记录最近十分钟间隔内使用的气体。我想将来自这两个记录器的数据合并到一个数据框中以进行绘图和分析,但时间并不完全一致。我希望每十分钟在数据框中有一行,日期时间显示时间段的开始。

温度记录器数据如下所示:

           datetime temperature
2010-09-30 06:58:53 78.996
2010-09-30 07:08:53 78.645
2010-09-30 07:18:53 78.514
2010-09-30 07:28:53 79.173
2010-09-30 07:38:53 78.602


气体记录仪数据如下所示:

           datetime gas
2010-09-30 13:45:00 0
2010-09-30 13:55:00 1
2010-09-30 14:05:00 0
2010-09-30 14:15:00 4
2010-09-30 14:25:00 2


我想以十分钟为间隔组合两个数据帧,以便组合数据如下所示:

           datetime temperature gas  
2010-09-30 13:40:00 NA 0
2010-09-30 13:50:00 78.996 1
2010-09-30 14:00:00 78.645 0
2010-09-30 14:10:00 78.514 4
2010-09-30 14:20:00 79.173 2
2010-09-30 07:38:53 78.602 NA


这是获取这两个数据框的一些代码:
temps <- data.frame(datetime=c("2010-09-30 06:58:53",
"2010-09-30 07:08:53","2010-09-30 07:18:53",
"2010-09-30 07:28:53","2010-09-30 07:38:53"),
temperature=c(78.996,78.645,78.514,79.173,78.602),
stringsAsFactors=FALSE)
temps$datetime <- strptime(temps$datetime, format="%Y-%m-%d %H:%M:%S")
gas <- data.frame(datetime=c("2010-09-30 13:45:00",
"2010-09-30 13:55:00","2010-09-30 14:05:00",
"2010-09-30 14:15:00","2010-09-30 14:25:00"),
gas=c(0,1,0,4,2),stringsAsFactors=FALSE)
gas$datetime <- strptime(temps$datetime, format="%Y-%m-%d %H:%M:%S")

最佳答案

使用 align.timexts .

library(xts)
xTemps <- align.time(xts(temps[,2],as.POSIXct(temps[,1])), n=600)
xGas <- align.time(xts(gas[,2],as.POSIXct(gas[,1])), n=600)
merge(xTemps,xGas)

关于r - 如何按时间间隔匹配数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139032/

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