2
votes

I have a dataset giving a timepoint at which the ID is leaving on a trip (begin.trip).

The IDs are divided in 2 groups (treated & control) and I would like to know if the treatment caused a problem in the circadian clock.

Therefore, I would like to make 'time' a categorical factor like:

  • ID leaves between 7 am and 7 pm --> "day"
  • ID leaves between 7 pm and 7 am --> "night"

I tried the function cut(), but since time is not numerical, this is not working.

I already managed to split my date+time variable using

data$Time=data.frame(do.call( rbind , strsplit( as.character(data$begin.trip) , " " ) )) 
1
Welcome to SO. Would you be able to provide a reproducible data? That will allow SO users to give you a hand.jazzurro
You don't need to insert your whole dataset here. Read this How to make a great R reproducible example?narendra-choudhary
Thanks a lot for the link!Astrid Deryckere

1 Answers

5
votes

There are lots of ways. One way is like this:

library(lubridate)

# Generate some fake data
n <- 20
id <- sample(1:10,n,replace=T)
dv <- as.POSIXct(runif(n,as.POSIXct("2015-01-01 00:00:00"),
                         as.POSIXct("2015-12-31 23:59:59")),
                         origin="1970-01-01 00:00:00")
tc <- sample(c("Treated","Control"),n,replace=T)

df <- data.frame( ID=id,Date=dv,Status=tc)

# Now classify the time
df$Hour <- hour(df$Date)
df$cat <- ifelse( df$Hour<7 | 19<df$Hour, "Night","Day" )

# Look at the results
df

which yields:

   ID                Date  Status Hour   cat
1   3 2015-08-19 21:01:13 Treated   21 Night
2   8 2015-08-10 23:36:43 Treated   23 Night
3   6 2015-12-11 10:10:09 Treated   10   Day
4   6 2015-09-18 02:06:04 Treated    2 Night
5   6 2015-05-03 03:43:38 Control    3 Night
6   4 2015-08-13 22:31:28 Control   22 Night
7   5 2015-12-06 20:12:26 Control   20 Night
8   3 2015-01-30 05:33:37 Control    5 Night
9   6 2015-05-21 17:14:14 Control   17   Day
10 10 2015-03-12 01:37:30 Treated    1 Night
11  5 2015-12-08 02:05:05 Treated    2 Night
12  6 2015-10-08 08:35:26 Control    8   Day
13  7 2015-04-12 17:44:22 Control   17   Day
14  9 2015-05-20 20:35:41 Treated   20 Night
15  3 2015-03-28 20:03:12 Control   20 Night
16 10 2015-09-11 15:33:59 Control   15   Day
17  4 2015-05-03 00:38:05 Treated    0 Night
18  7 2015-12-02 11:58:19 Control   11   Day
19  6 2015-03-15 15:46:23 Control   15   Day
20  3 2015-05-08 05:38:25 Treated    5 Night