我试图总结两个变量之间的时间差并找到列表的长度。
我的数据集看起来像这样。我想得到他们的差距低于6:00的步数。
Group Time1 Gap
A 11:00:00 AM
A 11:04:00 AM 4:00
A 11:06:00 AM 2:00
A 11:08:00 AM 2:00
A 11:12:00 AM 4:00
A 11:19:00 AM 7:00
A 11:26:00 AM 7:00
A 11:28:00 AM 2:00
A 11:30:00 AM 2:00
A 11:32:00 AM 2:00
A 11:34:00 AM 2:00
A 11:36:00 AM 2:00
最终结果应如下所示;
Group Gap Step
A 12:00 4
如果间隔大于6:00,我不想继续计算其他步骤。
我使用过滤器选项“...%>%过滤器(间隙< 8:00)%>%...”但它没有用。我知道切割点会将此列表分成两个独立的部分。
样本DF:
structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor"), Time1 = structure(1:12, .Label = c("11:00:00 AM",
"11:04:00 AM", "11:06:00 AM", "11:08:00 AM", "11:12:00 AM", "11:19:00 AM",
"11:26:00 AM", "11:28:00 AM", "11:30:00 AM", "11:32:00 AM", "11:34:00 AM",
"11:36:00 AM"), class = "factor"), Gap = structure(c(1L, 3L,
2L, 2L, 3L, 4L, 4L, 2L, 2L, 2L, 2L, 2L), .Label = c("", "2:00",
"4:00", "7:00"), class = "factor")), .Names = c("Group", "Time1",
"Gap"), class = "data.frame", row.names = c(NA, -12L))
答案 0 :(得分:2)
首先,您需要创建"步骤"列,只是行号减一。
a %>%
mutate(Step=row_number()-1) %>%
然后,您需要通过删除冒号从您给定的字符串中提取时间。 Str_replace来自library(stringr)
mutate(gap = as.numeric(str_replace(Gap, ":", ""))) %>%
过滤,仅保留间隙大于600的那些,相当于大于"6:00"
的时间。
filter(gap > 600) %>%
然后,只保留Group,Gap和Step。
select(Group, Gap, Step)
你的最终结果:
> df1 %>%
+ mutate(Step=row_number()-1) %>%
+ mutate(gap=as.numeric(str_replace(Gap, ":", ""))) %>%
+ filter(gap > 600) %>%
+ select(Group, Gap, Step)
Group Gap Step
1 A 12:00 5
答案 1 :(得分:2)
通过dplyr
,
library(dplyr)
df %>%
mutate(Time1 = as.POSIXct(Time1, format = '%H:%M:%S'), step = row_number()-1) %>%
filter(Time1 - lag(Time1) > 6)
# Group Time1 Gap step
#1 A 2017-05-21 11:24:00 12:00 5