Saturday, December 7, 2013

Initial Sleep Analysis

This is my first post sharing my initial analysis of my sleep data. I've collected data for two months now using Tasker on my Android phone. It collects the start and end date/time of each sleep period as well as why I woke up.

I've just started using R and love it. Here is the first graph showing the total number of hours slept each night. Weekends are colored red because I wanted to know if I slept better on the weekends (it doesn't seem to matter).

Here is the graph:
(click to view)
I had a few days in November where my tasker action didn't save all the sleep intervals. On those days, I added estimate data. I may remove those dates altogether. There may be other dates that are incomplete. I have a could of days with less than four hours and I can't remember if that is correct or not. That probably has an impact on the dip in sleep duration in November.

Generally, I am getting more sleep that I expected, averaging around 6.5 to 7 hours per night.

Next I need to factor in the number of sleep segments to come up with a measurement of sleep quality (greater duration and fewer segments represents better sleep). I also need to consider why I woke up. If I was interrupted by an alarm, for example, and that cut my sleep shorter than it would have been naturally, it's not necessarily fair to treat that as a dependent variable when considering factors that affect sleep quality.

Here is the R Script I used (via RStudio):
library(methods) 
library(lubridate)

sleep <- read.csv("C:/Users/xxxxxxx/Documents/R/Sleep/sleepdata.csv", header=T)

sleep["EndDate"] <- NA

sleep$EndDate <- ifelse(sleep$EndTime > 12, format(mdy(as.character(sleep$Date)) + days(1), format="%m-%d-%Y"), format(mdy(as.character(sleep$Date)), format="%m-%d-%Y"))  #fill column with date of the morning of each sleep period

sleep["Weekday"] <- NA

sleep$Weekday <- weekdays(mdy(sleep$EndDate))  #fill column with weekday of the sleep period

sleep  #display data in case I want to review

dailytotals <-unique(within(sleep, {
  Duration <- ave(Duration, EndDate, FUN=sum)rm(Date,StartTime,EndTime,Status)
}))  #create frame, one record per day with total number of hours slept

dailytotals  #display in case I want to review

ggplot(dailytotals, aes(x=EndDate, y=Duration, group=1, colour=Weekday)) +
  geom_point() +  #plot points on graph
  stat_smooth(level=.99) + #regression/curve line with 99% certainty range
  theme(axis.text.x = element_text(angle = 90), axis.title.x = element_text(angle = 0), axis.title.y = element_text(angle = 0)) +  #labels, turn x axis vertically
  scale_color_manual(values=c(Saturday="red", Sunday="red", Monday="blue", Tuesday="blue", Wednesday="blue", Thursday="blue", Friday="blue"))  #color code weekend days

No comments:

Post a Comment