The SleepCycles package  has been specifically developed to identify sleep cycles  and their corresponding NREM and REM components (known as (N)REM periods) from data that has been categorized based on AASM criteria for sleep staging .
In the other hand, the rsleep package reads and analyze sleep data in various formats.
This vignette describes how to combine
rsleep packages to identify sleep cycles in sleep data and
then leverage this material in sleep data analysis pipelines.
Sleep cycles can be identified from hypnograms.
contains a hypnogram scored by a sleep expert using Noxturnal software
published by ResMed. The rsleep package provides the
read_events_noxturnal() function to read hypnograms in this
SleepCycles package only reads directories and files
in specific format. Hypnograms must be converted in the appropriate
arrangement before being written on disk in an explicit folder:
events.vmrk = data.frame(Description = as.character(events$event)) events.vmrk$Description[events.vmrk$Description == "AWA"] = 0 events.vmrk$Description[events.vmrk$Description == "N1"] = 1 events.vmrk$Description[events.vmrk$Description == "N2"] = 2 events.vmrk$Description[events.vmrk$Description == "N3"] = 3 events.vmrk$Description[events.vmrk$Description == "REM"] = 5 events.vmrk$Description = as.integer(events.vmrk$Description) events.vmrk$Type = "SleepStage" events.vmrk = events.vmrk[,c(2,1)] newdir <- file.path( tempdir(),"SleepCycles") dir.create(newdir, showWarnings = FALSE) write.table( events.vmrk, file = paste( newdir, "events.txt", sep = "/"), row.names=FALSE, col.names = TRUE, quote = FALSE, sep = ",")
SleepCycles() function can now read the created
directory and detect sleep cycles in the saved hypnograms. The original
version of the function interactively asks the file format to the user
and writes the result to a file in the same directory. The forked
boupetch/SleepCycles modifies this behaviour to
take the format as parameters and return directly the results as a
dataframe, making the pipeline easier to automate.
Binding the resulting dataframe to the original hypnogram
events and performing aggregations provides valuable sleep
hypnogram.full = cbind(events, cycles) # Number of cycles max(hypnogram.full$SleepCycle, na.rm = TRUE) # Duration of each cycle hypnogram.agg = aggregate( event ~ SleepCycle, data = hypnogram.full, FUN = length) hypnogram.agg$minutes = hypnogram.agg$event/2 hypnogram.agg # Composition of each cycle cycles.comp = aggregate( SleepStages ~ SleepCycle + event, data = hypnogram.full, FUN = length) cycles.comp = reshape( data = cycles.comp, direction = "wide", timevar = "event", idvar = "SleepCycle") cycles.comp