将时间转换为“白天”和“夜晚”

Ast*_*ere 2 time datetime r

我有一个数据集,给出了 ID 离开旅行的时间点 (begin.trip)。

ID 分为 2 组(治疗组和对照组),我想知道治疗是否导致生物钟出现问题。

因此,我想让“时间”成为一个分类因素,例如:

  • ID 上午 7 点到晚上 7 点之间离开 --> “白天”
  • ID 晚上 7 点到早上 7 点之间离开 --> “夜间”

我尝试了该功能cut(),但由于时间不是数字,所以这不起作用。

我已经设法使用分割我的日期+时间变量

data$Time=data.frame(do.call( rbind , strsplit( as.character(data$begin.trip) , " " ) )) 
Run Code Online (Sandbox Code Playgroud)

Mik*_*ise 7

有很多方法。一种方法是这样的:

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
Run Code Online (Sandbox Code Playgroud)

产生:

   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
Run Code Online (Sandbox Code Playgroud)