ifelse using multiple conditions of time objects

24 views
Skip to first unread message

Renanel Pickholtz

unread,
Jul 17, 2018, 4:15:01 AM7/17/18
to Israel R User Group

Hello,

I seem to be stuck with what I thought should be a fairly simple task.

I have a data frame (~800,000 rows) with a timestamp (Datetime, also broken down to Date, and Time), and the time of Sunset, Sunrise, Dusk, Dawn, and Night for that specific date (from solar calculations). All columns are currently of class POSIXct.

 

 

head(solar_df)

  Datetime            Date       Time     Sunrise  Sunset   Dawn     Dusk     Night
1 2016-07-08 14:06:19 08/07/2016 14:06:19 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47
2 2016-07-08 14:08:23 08/07/2016 14:08:23 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47
3 2016-07-08 14:08:29 08/07/2016 14:08:29 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47
4 2016-07-08 14:08:46 08/07/2016 14:08:46 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47
5 2016-07-08 14:09:39 08/07/2016 14:09:39 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47
6 2016-07-08 14:11:24 08/07/2016 14:11:24 05:48:41 19:44:39 05:21:45 20:11:35 21:18:47

 

 

I want to add a column $Period by assigning each row with a single period as in the following examples:

If Time > Night & < Dawn = “Night”

If Time >= Dawn & < Sunrise = “Dawn”

If Time >= Sunrise & < Sunset = “Day”

 

I tried a nested ifelse function, but ifelse() messes up the POSIXct format, so comparing times becomes a serious problem. 

I also tried other time formats (using chron, lubridate), but can’t seem to hack it.

Help would be very much appreciated.

Michael Dorman

unread,
Jul 17, 2018, 4:19:31 AM7/17/18
to israel-r-...@googlegroups.com
No need for nested expressions, you can always do something like this - 

dat$Period = NA
dat$Period[dat$Time > dat$Night & dat$Time < dat$Dawn] = "Night"
dat$Period[dat$Time >= dat$Dawn & dat$Time < dat$Sunrise] = "Dawn"
dat$Period[dat$Time >= dat$Sunrise & dat$Time < dat$Sunset] = "Day"

--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-group+unsub...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Renanel Pickholtz

unread,
Jul 17, 2018, 5:04:10 AM7/17/18
to Israel R User Group
Thank you Michael,
I'm nearly embarrassed as I am relieved -  hadn't thought of it in such a straightforward manner.

Thank you
Reply all
Reply to author
Forward
0 new messages