【发布时间】: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 != " "。这样读对吗?如果是这样,那么是的。