简体   繁体   English

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

[英]Convert time to "day" and "night"

I have a dataset giving a timepoint at which the ID is leaving on a trip (begin.trip).我有一个数据集,给出了 ID 离开旅行的时间点 (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. ID 分为 2 组(治疗组和对照组),我想知道治疗是否会导致生物钟出现问题。
Therefore, I would like to make 'time' a categorical factor like:因此,我想让“时间”成为一个分类因素,例如:
- ID leaves between 7 am and 7 pm --> "day" - ID 在早上 7 点到晚上 7 点之间离开 --> “天”
- ID leaves between 7 pm and 7 am --> "night" - ID 在晚上 7 点到早上 7 点之间离开 --> “晚上”

I tried the function cut() , but since time is not numerical, this is not working.我尝试了函数cut() ,但由于时间不是数字,这不起作用。
I already managed to split my date+time variable using我已经设法使用拆分我的日期+时间变量
data$Time=data.frame(do.call( rbind , strsplit( as.character(data$begin.trip) , " " ) ))

I'm totally new to this html coding, so I have no idea how to insert my dataset.我对这个 html 编码完全陌生,所以我不知道如何插入我的数据集。

Hope you can help me out!希望你能帮帮我!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM