eabanoz
eabanoz

Reputation: 351

cut point according specific interval

I have tried to summarize time gap between two variables and find length of the list.

My data set looks like this. I would like to get numbers of steps that their gaps are lower than 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

End result should look like this;

Group   Gap   Step
    A   12:00  4

If interval is bigger than 6:00 I don't want to continue to count other steps.

I used filter option "... %>% filter(gap < 8:00)%>% ..." but it didn't work. I understand that cut point will split this list into two separate parts.

Sample 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))

Upvotes: 0

Views: 190

Answers (2)

Sotos
Sotos

Reputation: 51592

Another way via 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

Upvotes: 2

Julian Zucker
Julian Zucker

Reputation: 564

First, you need to create the "Step" column, which is just the row number minus one.

a %>% 
  mutate(Step=row_number()-1) %>%

Then, you need to extract the time from your given string, by removing the colon. Str_replace is from library(stringr)

mutate(gap = as.numeric(str_replace(Gap, ":", ""))) %>%

Filter, keeping only those where gap is greater than 600, which corresponds to a time greater than "6:00".

filter(gap > 600) %>%

Then, keep only Group, Gap, and Step.

select(Group, Gap, Step)

Your final output:

    > 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

Upvotes: 2

Related Questions