计算R中的相对时间序列

时间:2014-08-06 13:41:38

标签: r datetime for-loop time-series

我有一个数据框(下面的示例),我希望将其传递给一个函数,该函数将采用绝对时间值(采用POSIXct格式)并将它们转换为相对时间序列。

ID          Observation
M97         11/09/2013 10:35
M97         11/09/2013 13:13

我没有R功能的经验,所以我很难全身心地写下它。我已经开始使用一些伪代码(如下所示)来给出我想要做的概念。

relative_time <- function(df) {
    #for each row in the dataframe:
        #subtract the Observation value from the Observation value of the first row
        #Append the returned value to the end of the row in a new column called RelativeTime
}

我想要实现的输出如下:

ID          Observation         RelativeTime
M97         11/09/2013 10:35    0
M97         11/09/2013 13:13    148

我已经查看了this question等等。但是因为&#34; for循环&#34;的R语法而被卡住了。扔我。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

使用diff但填充零,因为差异比数据点少一个。让我们使用R&#39的POSIXct日期类来创建数据框:

> d=data.frame(Observation=as.POSIXct(c("2014-08-06 14:46:14 BST","2014-08-06 14:36:14 BST","2014-08-06 16:56:14 BST")))
> d
          Observation
1 2014-08-06 14:46:14
2 2014-08-06 14:36:14
3 2014-08-06 16:56:14

不需要循环:

> d$RelativeTime = c(0,diff(d$Observation))
> d
          Observation RelativeTime
1 2014-08-06 14:46:14            0
2 2014-08-06 14:36:14          -10
3 2014-08-06 16:56:14          140

注意这些差异是几分钟,如果你想要秒:

> d$RelativeTime = c(0,diff(d$Observation)*60)
> d
          Observation RelativeTime
1 2014-08-06 14:46:14            0
2 2014-08-06 14:36:14         -600
3 2014-08-06 16:56:14         8400