Need to calculate the SD of sleep bedtime using 24 hour time with some observations after midnight

52 views Asked by At

I am getting sleep times and converting them to minutes to then calculate the standard deviation between bedtimes on different days. The issue is that some days the bedtime is after midnight. I got it to work on R but need the SAS code.


install.packages("chron")
library(chron)


data <- read.table(text="
sleep_time wake_time
23:30:00 05:30:00
00:00:00 05:30:00
00:30:00 05:35:00
", header=T)

mean(times(data$wake_time))
mean(times(data$sleep_time))


wake<- times(data$wake_time)
sleep <- times(data$sleep_time)
times(mean(ifelse(sleep <wake, sleep+1, sleep)))

sd(ifelse(sleep < wake, sleep+1, sleep) * 24*60)
1

There are 1 answers

0
PBulls On

This code reproduces what you're doing in R, with the following points of attention:

  • ifn is the (numeric) SAS version of ifelse. The unit is seconds here, so we're adding 24 x 60 x 60 rather than 1 (day). There's many other ways to conditionally do this addition.
  • Similarly, the standard deviation is calculated in seconds, so dividing by 60 gives the result in minutes.
  • I'm using PROC SQL here but there's many other ways to get summary statistics.
data times;
   input SLEEP TIME. WAKE TIME.;
   format SLEEP WAKE TOD8.;
   BEDTIME = ifn(sleep < wake, sleep + 24*60*60, sleep);
   * works too: BEDTIME = sleep + (sleep < wake)*24*60*60 ;
   cards;
23:30:00 05:30:00
00:00:00 05:30:00
00:30:00 05:35:00
;
run;

proc sql;
   select mean(bedtime) as M format TOD8., std(bedtime)/60 as S from times;
quit;

*         M     S  ;
*  --------------  ;
*  00:00:00    30  ;