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) |
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