【问题标题】:Merge irregular time series data sets合并不规则时间序列数据集
【发布时间】:2017-02-14 18:41:47
【问题描述】:

我正在尝试合并几个数据集。但是,每个都有不规则的每小时时间戳。我的目标是在同一小时间隔内合并数据,并填写常规时间序列时间表。例如,您可以看到两个数据集:

 x <- structure(list(Date = structure(1:5, .Label = c("09.09.2011 21:54", 
"09.09.2011 22:59", "09.10.2011 00:04", "09.10.2011 01:09", "09.10.2011 02:14"
), class = "factor"), hexane = c(0, 0, 0, 0, 0), benzene = structure(c(1L, 
2L, 4L, 3L, 5L), .Label = c("0", "4.4", "4.7", "6.3", "7.7"), class = "factor"), 
    toluene = c(2.2, 2.6, 3.5, 2.7, 3.1)), .Names = c("Date", 
"hexane", "benzene", "toluene"), row.names = c(NA, 5L), class = "data.frame")
> 

    y <- structure(list(Date = structure(1:5, .Label = c("09.09.2011 21:54", 
"09.09.2011 22:59", "09.10.2011 00:04", "09.10.2011 01:09", "09.10.2011 02:14"
), class = "factor"), ethane = c(14.4, 868.9, 547, 491.4, 56.1
), propane = c(6.4, 32.1, 23.7, 22.8, 7.2), isobutane = c(1.7, 
2, 1.8, 1.3, 1.1), n.butane = c(3.1, 3, 3.7, 4.3, 2.9), isopentane = c(5.6, 
3, 2.4, 3.4, 2.7), n.pentane = c(1.4, 2.4, 2.3, 2.4, 2.3)), .Names = c("Date", 
"ethane", "propane", "isobutane", "n.butane", "isopentane", "n.pentane"
), row.names = c(NA, 5L), class = "data.frame")

na.fill (x, NA)
na.fill (y, NA

)

#identify "Date" column

x <- as.POSIXct(x$Date,format='%m.%d.%y %H:%M')
y <- as.POSIXct(y$Date,format='%m.%d.%y %H:%M')

#merge two data sets

merged_data <- merge.data.frame(x, y, by='Date', all=TRUE)

但是,输出文件“merged_data”上的日期列填充了 NA。我需要在 Date 列上设置一个每小时固定的时间戳。

The aimed output file

【问题讨论】:

  • 无论是我还是您提供的输入数据都遗漏了一些东西。 merge_date$Date 列用 NA 填充,因为 x$Date 和 y$Dat 以 NA 开头。
  • @GGamba 抱歉,我现在修好了。

标签: r


【解决方案1】:

您的 merge_date$Date 为 NA,因为转换为 POSIXct 失败。 有两个步骤可以得到你的结果。

  1. 将您的 dfs 的 Date 列转换为实际的 Date 对象
  2. 四舍五入(或截断)到小时并加入两个 dfs

转换为日期

有几种方法:

as.POSIXct

x$Date <- as.POSIXct(x$Date, format = '%m.%d.%Y %H:%M')

注意 4 位数年份的大写 Y

strptime

和上面差不多

x$Date <- strptime(x$Date, format = '%m.%d.%Y %H:%M')

随时

使用很棒的anytime 包-让我非常头疼-

x$Date <- anytime(x$Date)

四舍五入并加入

x$Date <- anytime(x$Date)
y$Date <- anytime(y$Date)

x$Date <- format(x$Date, '%m/%d/%y %H')
y$Date <- format(y$Date, '%m/%d/%y %H')

merge(x, y, by = Date)

Date          hexane benzene toluene ethane propane isobutane n.butane isopentane n.pentane
# 09/09/11 21      0       0     2.2   14.4     6.4       1.7      3.1        5.6       1.4
# 09/09/11 22      0     4.4     2.6  868.9    32.1       2.0      3.0        3.0       2.4
# 09/10/11 00      0     6.3     3.5  547.0    23.7       1.8      3.7        2.4       2.3
# 09/10/11 01      0     4.7     2.7  491.4    22.8       1.3      4.3        3.4       2.4
# 09/10/11 02      0     7.7     3.1   56.1     7.2       1.1      2.9        2.7       2.3

希望对你有帮助

【讨论】:

  • 非常感谢,“anytime”包非常有用。几乎解决了。我只是想知道为什么日期列切换到最新到最旧。原始数据从最旧到最新。感谢您的宝贵时间!
  • 不在您在示例中放置的数据中,AFAIK。如果有帮助,请考虑投票并接受答案
猜你喜欢
  • 2013-11-07
  • 1970-01-01
  • 2015-06-04
  • 2011-10-28
  • 2020-05-07
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
相关资源
最近更新 更多