user6678274 user6678274 - 1 year ago 99
R Question

How to subset over a string of times

In R I have a dataframe


head (data) gives
ID sign_in
21 23:50:21
12 10:11:38

that contains ID and the sign in time for that ID. Both columns are strings (or characters).
Say I want a subset of
that only contains ID in the time interval from 10 o'clcok to 11 o'clock.

This is how I tried to solve it:

data_new = subset(data, data[,2] %in% as.character(10:00:00) : as.character(11:00:00) )

but R gives an error message saying ERROR: unexpected constant

How can I solve this?

Answer Source

You can convert the character column to "POSIXct" "POSIXt" format by,

df$sign_in <- as.POSIXct(df$sign_in,format="%H:%M:%S") 

and then subset,

df[df$sign_in > as.POSIXct("10:00:00", format="%H:%M:%S") &
     df$sign_in < as.POSIXct("11:00:00", format="%H:%M:%S"), ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download