0

I am trying to create a new categorical variable that shows whether an observation Time falls between dawn and dusk times gathered from suncalc. For example. All three variables currently class character. I have tried both as.factor() and as.POSIXIt() operators but haven't found the magic words yet.

#       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

to make

#       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

I have tried both several ifelse statements and lubridate functions but nothing seems to work. I am probably doing both those things wrong or I am just not thinking of something. Any help will be appreciated. Thanks.

disclaimer: first post on stackoverflow, if I am doing it wrong please tell me for any future posts!

CSk9
  • 69
  • 3

1 Answers1

0

Base R doesn't have a class for time only data, but the chron package does.

You can use the times function in the chron package along with an ifelse, like this...

#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

See also relevant posts:

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

Storing time without date but not as class character

Chris Holbrook
  • 2,531
  • 1
  • 17
  • 30