Skip to content

Instantly share code, notes, and snippets.

@ryanpraski
Created July 26, 2017 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanpraski/280efe42f53d8627b006f3266dcb3584 to your computer and use it in GitHub Desktop.
Save ryanpraski/280efe42f53d8627b006f3266dcb3584 to your computer and use it in GitHub Desktop.
library(dplyr)
library(ggplot2)
library(lubridate)
library(XML)
#load apple health export.xml file
xml <- xmlParse("C:\\Users\\praskry\\Desktop\\export_sleep.xml")
#transform xml file to data frame - select the Record rows from the xml file
df <- XML:::xmlAttrsToDataFrame(xml["//Record"])
str(df)
#make value variable numeric
#df$value <- as.numeric(as.character(df$value))
#str(df)
#make startDate in a date time variable POSIXct using lubridate with eastern time zone
#Europe/Zurich
df$startDate <-ymd_hms(df$startDate,tz="Europe/Zurich")
df$endDate <-ymd_hms(df$endDate,tz="Europe/Zurich")
str(df)
##add in sleep seconds endDate-startDate
df$sleepSeconds<-(df$endDate - df$startDate)
##add in hours sleep endDate-startDate difftime
df$sleepHours <- with(df, difftime(endDate,startDate,units="hours") )
#convert difftime to numeric
df$sleepHours <- as.numeric(df$sleepHours)
##add in year month date dayofweek hour columns
##make date the day before so you can see when you went to sleep #86400 seconds in a day
df$date<-format(df$endDate-86400,"%Y-%m-%d")
str(df)
##In Bed Hours By Date
df %>%
filter(value == 'HKCategoryValueSleepAnalysisInBed' & sourceName == 'Connect') %>%
group_by(date) %>%
summarize(sleepHours=sum(sleepHours)) %>%
#print table in bed sleepHours
print (n=150) %>%
#graph data by month by year
ggplot(aes(x=date, y=sleepHours)) +
geom_bar(position='dodge', stat='identity') +
scale_y_continuous(labels = scales::comma) +
scale_fill_brewer() +
theme_bw() +
theme(panel.grid.major = element_blank())+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
##Asleep Hours By Date
df %>%
filter(value == 'HKCategoryValueSleepAnalysisAsleep' & sourceName == 'Connect') %>%
group_by(date) %>%
summarize(sleepHours=sum(sleepHours)) %>%
#print table in bed sleepHours
print (n=150) %>%
#graph data by month by year
ggplot(aes(x=date, y=sleepHours, group = 1)) +
geom_line() +
theme(panel.grid.major = element_blank())+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment