【问题标题】:Convert time to "day" and "night"将时间转换为“白天”和“夜晚”
【发布时间】:2016-04-08 04:20:59
【问题描述】:

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

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

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

  • 身份证在早上 7 点到晚上 7 点之间离开 --> “天”
  • 身份证在晚上 7 点到早上 7 点之间离开 --> “晚上”

我尝试了函数cut(),但由于时间不是数字,这不起作用。

我已经设法使用

拆分我的日期+时间变量
data$Time=data.frame(do.call( rbind , strsplit( as.character(data$begin.trip) , " " ) )) 

【问题讨论】:

  • 欢迎来到 SO。你能提供一个可重现的数据吗?这将允许 SO 用户帮助您。
  • 您不需要在此处插入整个数据集。阅读此How to make a great R reproducible example?
  • 非常感谢您的链接!

标签: r datetime time


【解决方案1】:

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

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

产生:

   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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多