Jack
Jack

Reputation: 722

Subset Dataframe given time R

Given a dataframe that looks like the following:

Time    Delay   Station1
6:00:15 0:00:00 12
6:15:22 0:00:00 41
6:16:52 0:00:00 40
6:30:19 0:00:00 31
6:31:22 0:00:00 40
6:32:08 0:01:20 35
6:45:25 0:00:30 55
6:47:21 0:00:20 50
6:48:10 0:01:10 43
6:52:00 0:00:00 53
7:01:24 0:00:30 37
7:02:13 0:00:30 40
7:04:58 0:00:40 34
7:05:40 0:02:20 35
7:19:41 0:00:30 59
7:24:00 0:01:10 42
7:25:08 0:00:50 47
7:23:16 0:01:20 37

How can I subset the dataframe for times between 6:00 and 7:00? All the answers I found contain, the date as well and this is a bit confusing.

So far, amongst other things, I did the following:

df.route1 <- read.table("my.data.csv",  header = T, sep = ';',stringsAsFactors = FALSE)
subset(df.route1, format(Time, "%H:%M:%S") >= "06:00" & format(Time, "%H:%M:%S") < "07:00")

Any suggestions?

Upvotes: 0

Views: 60

Answers (2)

BrianKfromMN
BrianKfromMN

Reputation: 44

require(lubridate)
df$time <- strptime(x = as.character(df$time), format = "%H:%M:%S")
df[(hour(df$time) >= 6 & hour(df$time) < 7), ]

Upvotes: 1

Rolando Tamayo
Rolando Tamayo

Reputation: 286

You can do it:

library(tibble)

data<-tribble(~Time,    ~Delay,   ~Station1,
              "6:00:15","0:00:00","12",
              "6:15:22","0:00:00","41",
              "6:16:52","0:00:00"," 40",
              "6:30:19","0:00:00"," 31",
              "6:31:22"," 0:00:00"," 40",
              "6:32:08"," 0:01:20"," 35",
              "6:45:25"," 0:00:30"," 55",
              "6:47:21"," 0:00:20"," 50",
              "6:48:10"," 0:01:10"," 43",
              "6:52:00"," 0:00:00"," 53",
              "7:01:24"," 0:00:30"," 37",
              "7:02:13"," 0:00:30"," 40",
              "7:04:58"," 0:00:40"," 34",
              "7:05:40"," 0:02:20"," 35",
              "7:19:41"," 0:00:30"," 59",
              "7:24:00"," 0:01:10"," 42",
              "7:25:08"," 0:00:50"," 47",
              "7:23:16"," 0:01:20"," 37")
library(lubridate)
library(dplyr)

datadata$Time<-hms(data$Time)
filter(data,Time>=hms("6:00:00")&Time<=hms("7:00:00"))

# A tibble: 10 x 3
           Time    Delay Station1
   <S4: Period>    <chr>    <chr>
 1    6H 0M 15S  0:00:00       12
 2   6H 15M 22S  0:00:00       41
 3   6H 16M 52S  0:00:00       40
 4   6H 30M 19S  0:00:00       31
 5   6H 31M 22S  0:00:00       40
 6    6H 32M 8S  0:01:20       35
 7   6H 45M 25S  0:00:30       55
 8   6H 47M 21S  0:00:20       50
 9   6H 48M 10S  0:01:10       43
10    6H 52M 0S  0:00:00       53

Upvotes: 0

Related Questions