【问题标题】:Conditionally calculate time differences between rows in R有条件地计算R中行之间的时间差
【发布时间】:2016-05-02 19:16:36
【问题描述】:

我正在尝试计算行与具有满足某些条件的列的行之间的时间差。

读入一些数据:

my_data <- data.frame(criteria = c("some text", "some more text", " ", " ", "more text", " "),
                  timestamp = as.POSIXct(c("2015-07-30 15:53:15", "2015-07-30 15:53:47", "2015-07-30 15:54:48", "2015-07-30 15:55:48", "2015-07-30 15:56:48", "2015-07-30 15:57:49")))

        criteria           timestamp
1      some text 2015-07-30 15:53:15
2 some more text 2015-07-30 15:53:47
3                2015-07-30 15:54:48
4                2015-07-30 15:55:48
5      more text 2015-07-30 15:56:48
6                2015-07-30 15:57:49

我想获取每行与条件列中非空白的最后一行之间的时间差(以分钟为单位)。因此,我想要:

        criteria           timestamp time_diff
1      some text 2015-07-30 15:53:15         0
2 some more text 2015-07-30 15:53:47         0
3                2015-07-30 15:54:48         1
4                2015-07-30 15:55:48         2
5      more text 2015-07-30 15:56:48         0
6                2015-07-30 15:57:49         1

到目前为止,我已经构建了代码来识别“0”应该在哪里 - 我只需要代码来填充时间差异。这是我的代码:

my_data$time_diff <- ifelse (my_data$criteria != "", # Here's our statement
  my_data$time_diff <- "0", # Here's what happens if statement is TRUE
  my_data$time_diff <- NEED CODE HERE # if statement FALSE
  )

我有一种感觉,如果不是 ifelse 语句,那么这项工作可能会更好地执行,但我对 R 比较陌生。

我在这里找到了 q's,个人试图获取相邻行之间的时间差(例如 here 和 here),但还没有找到试图处理这种情况的人。

我发现的最接近我的问题是this one,但这些数据与我的个人想要处理它们的方式不同(至少从我的角度来看)。

编辑:大写标题。

【问题讨论】:

  • 似乎对于每个“时间戳”,您都需要分别与cummax((my_data$criteria != " ") * seq_len(nrow(my_data))) 处的“时间戳”的时间差?
  • @alexis_laz,我想是的。为了澄清您的意思,我将每个时间戳(例如“timestamp3”)与最大行号的时间戳进行比较 “timestamp3” 其中 my_data$criteria != " " 。这样读对吗?如果是这样,那么是的。

标签: r datetime posixct


【解决方案1】:

用 alexis_laz 精湛的表达完成答案:

my_data <- data.frame(criteria = c("some text", "some more text", " ", " ", "more text", " "),
                      timestamp = as.POSIXct(c("2015-07-30 15:53:15", "2015-07-30 15:53:47", "2015-07-30 15:54:48", "2015-07-30 15:55:48", "2015-07-30 15:56:48", "2015-07-30 15:57:49")))

my_data$time_diff <- 
  my_data$timestamp - 
  my_data[cummax((my_data$criteria != " ") * seq_len(nrow(my_data))), 'timestamp']

my_data

        criteria           timestamp time_diff
1      some text 2015-07-30 15:53:15    0 secs
2 some more text 2015-07-30 15:53:47    0 secs
3                2015-07-30 15:54:48   61 secs
4                2015-07-30 15:55:48  121 secs
5      more text 2015-07-30 15:56:48    0 secs
6                2015-07-30 15:57:49   61 secs

【讨论】:

  • 作为一个额外的说明,difftime 在这里也可以派上用场,它的 units = "mins" 参数
猜你喜欢
  • 1970-01-01
  • 2020-10-25
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多