如何根据时间 object 是否落在另外两个时间 object 之间来创建分类变量

How to make a categorical variable based on whether a time object falls between two other time objects

我正在尝试创建一个新的分类变量来显示观察时间是否介于黎明和从 suncalc 收集的 dusk 时间之间。例如。所有三个变量当前都是 class 个字符。我已经尝试了 as.factor()as.POSIXIt() 运算符,但还没有找到神奇的词。

#       Time     dawn     dusk
# 1 19:59:05 05:59:12 21:12:01
# 2 18:46:05 05:51:25 21:21:48
# 3 07:50:21 07:42:54 18:54:53
# 4 10:19:00 04:37:52 21:38:02
# 5 12:16:35 04:39:50 21:39:02
# 6 09:34:26 07:02:49 18:32:55

制作

#       Time     dawn     dusk     daynight
# 1 23:59:05 05:59:12 21:12:01        night
# 2 18:46:05 05:51:25 21:21:48          day
# 3 07:50:21 07:42:54 18:54:53          day
# 4 10:19:00 04:37:52 21:38:02          day
# 5 02:16:35 04:39:50 21:39:02        night
# 6 09:34:26 07:02:49 18:32:55          day

我已经尝试了几个 ifelse 语句和 lubridate 函数,但似乎没有任何效果。我可能这两件事都做错了,或者我只是没有想到什么。任何帮助将不胜感激。谢谢。

免责声明:首先 post 在 Whosebug 上,如果我做错了,请告诉我以后 posts!

Base R 没有 class 时间数据,但 chron 包有。

您可以使用 chron 包中的 times 函数以及 ifelse,像这样...

#read data
x <- read.table(text = "
  Time     dawn     dusk
  23:59:05 05:59:12 21:12:01 
  18:46:05 05:51:25 21:21:48
  07:50:21 07:42:54 18:54:53
  10:19:00 04:37:52 21:38:02
  02:16:35 04:39:50 21:39:02
  09:34:26 07:02:49 18:32:55
", header = TRUE)

library(chron) #for times

#coerce character-formatted times to times (time-only) class
x$Time <- times(x$Time)
x$dawn <- times(x$dawn)
x$dusk <- times(x$dusk)

#use ifelse to assign conditional label
x$daynight <- with(x, ifelse(Time >= dawn & Time < dusk, "day", "night"))

#> x
#      Time     dawn     dusk daynight
#1 23:59:05 05:59:12 21:12:01    night
#2 18:46:05 05:51:25 21:21:48      day
#3 07:50:21 07:42:54 18:54:53      day
#4 10:19:00 04:37:52 21:38:02      day
#5 02:16:35 04:39:50 21:39:02    night
#6 09:34:26 07:02:49 18:32:55      day

另请参阅相关帖子:

Want only the time portion of a date-time object in R

Storing time without date but not as class character