【问题标题】:Calculating relative time series in R在 R 中计算相对时间序列
【发布时间】:2014-09-29 11:32:02
【问题描述】:

我有一个数据框(下面的示例),我想将它传递给一个函数,该函数将采用绝对时间值(采用 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 以及其他内容。但我被困住了,因为“for 循环”的 R 语法让我很困惑。

非常感谢任何帮助!

【问题讨论】:

  • 您的时间值是 R 的日期类之一还是字符串?
  • @Spacedman 好问题!它们在 POSIXct 中,我已经转换了它们。

标签: r datetime for-loop time-series


【解决方案1】:

使用diff,但用零填充,因为差异比数据点少一个。让我们使用 R 的 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

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2016-06-03
    • 2022-06-15
    相关资源
    最近更新 更多