| Title: | Sleep Data Filtering and Visualisation |
|---|---|
| Description: | An online app and command-line utility to import, filter and visualise sleep data. Can be used with sleep data collected from any type of device (e.g. radar, sleep diary,...) as long as the data contains sleep onset and wake-up times for each sleep session. |
| Authors: | Daniel Thedie [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-1352-7245>) |
| Maintainer: | Daniel Thedie <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.1.3 |
| Built: | 2026-06-23 09:28:45 UTC |
| Source: | https://github.com/chronopsychiatry/ambient-bd-nocturn |
Checks whether all the packages in Suggests are installed and prompts for install if not.
check_suggests()check_suggests()
No return value, called for side effects
Other internal:
get_col(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
This function calculates the Chronotype metric based on the mid-sleep time If sleep duration on free days is greater than on workdays, it applies a correction as described in Roenneberg et al. (2019).
chronotype(sessions)chronotype(sessions)
sessions |
The sessions data frame |
This function uses columns:
time_at_midsleep
sleep_period
is_workday
The Chronotype value in hours
Other sleep metrics:
composite_phase_deviation(),
interdaily_stability(),
sleep_regularity_index(),
social_jet_lag()
chronotype(example_sessions)chronotype(example_sessions)
Clean epoch data
clean_epochs(epochs)clean_epochs(epochs)
epochs |
A dataframe containing the epoch data |
The cleaned-up epochs dataframe
epochs <- clean_epochs(nocturn::example_epochs) clean_epochs(example_epochs)epochs <- clean_epochs(nocturn::example_epochs) clean_epochs(example_epochs)
Clean session data
clean_sessions(sessions)clean_sessions(sessions)
sessions |
A dataframe containing the session data |
The cleaned-up sessions dataframe
sessions <- clean_sessions(nocturn::example_sessions) clean_sessions(example_sessions)sessions <- clean_sessions(nocturn::example_sessions) clean_sessions(example_sessions)
This function calculates the Composite Phase Deviation (CPD) metric, used to measure the regularity of the sleep patterns.
composite_phase_deviation(sessions)composite_phase_deviation(sessions)
sessions |
The sessions data frame |
This function uses columns:
time_at_midsleep
is_workday
night
The Composite Phase Deviation (CPD) value
Other sleep metrics:
chronotype(),
interdaily_stability(),
sleep_regularity_index(),
social_jet_lag()
composite_phase_deviation(example_sessions)composite_phase_deviation(example_sessions)
A data frame containing epoch data recorded by a Somnofy device.
example_epochsexample_epochs
example_epochsA data frame with 18,755 rows and 15 columns. Each row represents a time-point (or epoch) in a session. Epochs are 30 seconds long. The columns are as follows:
timestamp: The time at which the epoch was recorded in UTC.
subject_id: The ID of the subject.
signal_quality_mean: The mean signal quality of the epoch.
movement_fast_mean: The mean movement detected during the epoch.
movement_fast_nonzero_pct
distance_mean: the distance of the subject from the device in meters.
motion_data_count: The number of data points in the epoch (30).
light_ambient_mean: The ambient light level during the epoch.
sound_amplitude_mean: The sound amplitude during the epoch.
temperature_ambient_mean: The ambient temperature during the epoch.
humidity_mean: The ambient humidity during the epoch.
pressure_mean: The ambient pressure during the epoch.
indoor_air_quality_mean: The indoor air quality during the epoch.
epoch_duration: The precise duration of the epoch (seconds).
sleep_stage: The sleep stage as established with the VT algorithm. They are encoded as numbers 0-5
data-raw/example_epochs.csv
A data frame containing epoch data recorded by a Somnofy device.
example_epochs_v1example_epochs_v1
example_epochs_v1A data frame with 1,373 rows and 16 columns. The corresponding session ID is contained in the file name. Each row represents a time-point (or epoch) in a session. Epochs are 30 seconds long. The columns are as follows:
timestamp: The time at which the epoch was recorded in UTC.
signal_quality_mean: The mean signal quality of the epoch.
movement_fast_mean: The mean movement detected during the epoch.
movement_fast_nonzero_pct
distance_mean: the distance of the subject from the device in meters.
motion_data_count: The number of data points in the epoch (30).
light_ambient_mean: The ambient light level during the epoch.
sound_amplitude_mean: The sound amplitude during the epoch.
temperature_ambient_mean: The ambient temperature during the epoch.
humidity_mean: The ambient humidity during the epoch.
pressure_mean: The ambient pressure during the epoch.
indoor_air_quality_mean: The indoor air quality during the epoch.
epoch_duration: The precise duration of the epoch (seconds).
sleep_stage: The sleep stage as established with the VT algorithm. They are encoded as numbers 0-5
data-raw/SEtXSxcMEhYXKQAA.example_epochs_v1.csv
A data frame containing sessions recorded by a Somnofy device.
example_sessionsexample_sessions
example_sessionsA data frame with 124 rows and 60 columns. Each row represents a session. Columns contain metadata about the session, including:
session_start: The start time of the session in UTC.
session_end: The end time of the session in UTC.
subject_id: The ID of the subject.
device_serial_number: The serial number of the device used.
time_at_sleep_onset: The time at which the subject fell asleep.
time_at_wakeup: The time at which the subject woke up. Columns also include various metrics averaged over the session, such as:
mean heart rate
mean respiration rate Finally, some columns contain environmental parameters, such as:
Temperature
Humidity
Light intensity
Noise level
Atmospheric pressure
data-raw/example_sessions.csv
A data frame containing sessions recorded by a Somnofy device.
example_sessions_v1example_sessions_v1
example_sessions_v1A data frame with 87 rows and 70 columns. Each row represents a session. Columns contain metadata about the session, including:
user_id: The ID of the recorded subject.
sex: The sex of the recorded subject.
birth_year: The year of birth of the recorded subject.
session_start: The start time of the session in UTC.
session_end: The end time of the session in UTC.
time_at_sleep_onset: The time at which the subject fell asleep.
time_at_wakeup: The time at which the subject woke up. Columns also include various metrics averaged over the session, such as:
mean heart rate
mean respiration rate Finally, some columns contain environmental parameters, such as:
Temperature
Humidity
Light intensity
Noise level
Atmospheric pressure
data-raw/example_sessions_v1.csv
Filter sessions by age range
filter_by_age_range( sessions, min_age = NULL, max_age = NULL, return_mask = FALSE )filter_by_age_range( sessions, min_age = NULL, max_age = NULL, return_mask = FALSE )
sessions |
The sessions dataframe |
min_age |
The minimum age of the subjects (inclusive) |
max_age |
The maximum age of the subjects (inclusive) |
return_mask |
If TRUE, returns a logical vector indicating which sessions belong to subjects within the specified age range |
This function uses columns:
birth_year
night
The sessions dataframe with only the sessions that belong to subjects within the specified age range,
or a logical vector if return_mask is TRUE
Other filtering:
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- filter_by_age_range(example_sessions_v1, min_age = 11, max_age = 18)filtered_sessions <- filter_by_age_range(example_sessions_v1, min_age = 11, max_age = 18)
Filter sessions for nights within a night range
filter_by_night_range(sessions, from_night, to_night, return_mask = FALSE)filter_by_night_range(sessions, from_night, to_night, return_mask = FALSE)
sessions |
The sessions dataframe |
from_night |
The start night of the range (inclusive) in YYYY-MM-DD format |
to_night |
The end night of the range (inclusive) in YYYY-MM-DD format |
return_mask |
If TRUE, returns a logical vector indicating which sessions meet the night range requirement |
This function uses columns:
night
The sessions dataframe with only the sessions that fall within the specified night range, or a logical vector if return_mask is TRUE
Other filtering:
filter_by_age_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- filter_by_night_range(example_sessions, "2025-04-07", "2025-04-10")filtered_sessions <- filter_by_night_range(example_sessions, "2025-04-07", "2025-04-10")
Filter by sex
filter_by_sex(sessions, sex, return_mask = FALSE)filter_by_sex(sessions, sex, return_mask = FALSE)
sessions |
The sessions dataframe |
sex |
The sex to filter for (M, F, or NULL for both) |
return_mask |
If TRUE, returns a logical vector indicating which sessions belong to the specified sex |
This function uses columns:
sex
The sessions dataframe with only the sessions that belong to the specified sex, or a logical vector if return_mask is TRUE
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- filter_by_sex(example_sessions_v1, "M")filtered_sessions <- filter_by_sex(example_sessions_v1, "M")
Filter epochs based on session IDs
filter_epochs_from_sessions(epochs, sessions, return_mask = FALSE)filter_epochs_from_sessions(epochs, sessions, return_mask = FALSE)
epochs |
The epochs dataframe |
sessions |
The sessions dataframe |
return_mask |
If TRUE, returns a logical vector indicating which epochs belong to the specified sessions |
This function uses sessions columns:
id
And epoch columns:
session_id
The epochs dataframe with only the epochs that belong to the specified sessions, or a logical vector if return_mask is TRUE
filter_by_night_range() to filter sessions by night range.
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
# Apply filtering to sessions to keep specific nights, and filter epochs accordingly filtered_sessions <- filter_by_night_range(example_sessions, "2025-04-07", "2025-04-10") filtered_epochs <- filter_epochs_from_sessions(example_epochs, filtered_sessions)# Apply filtering to sessions to keep specific nights, and filter epochs accordingly filtered_sessions <- filter_by_night_range(example_sessions, "2025-04-07", "2025-04-10") filtered_epochs <- filter_epochs_from_sessions(example_epochs, filtered_sessions)
Retrieve a column from a dataframe. If the column does not exist or is NULL, it returns a vector of NULLs of the same length as the number of rows in the dataframe.
get_col(df, col)get_col(df, col)
df |
A dataframe |
col |
The name of the column to retrieve |
A vector containing the values of the specified column, or a vector of NULLs if the column does not exist
Other internal:
check_suggests(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
get_col(example_sessions, "session_start")get_col(example_sessions, "session_start")
Dispatch to the appropriate function based on the dataframe type attribute (expecting "sessions" or "epochs").
get_colnames(df)get_colnames(df)
df |
A data frame containing either sessions or epochs data |
A named list of column names
Other internal:
check_suggests(),
get_col(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
get_colnames(example_sessions)get_colnames(example_sessions)
This function retrieves the standard column names for epochs data. If the column names are not set as an attribute, it attempts to infer them from a list of common column names.
get_epoch_colnames(epochs)get_epoch_colnames(epochs)
epochs |
A data frame containing epochs data |
A named list of column names
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
get_epoch_colnames(example_epochs)get_epoch_colnames(example_epochs)
Display the number of sessions in the epoch data, as well as the start and end dates of the epoch data
get_epochs_summary(epochs)get_epochs_summary(epochs)
epochs |
The epochs dataframe |
This function uses columns:
timestamp
session_id
A single-row dataframe summarising epoch information
get_sessions_summary() to summarise session information.
Other data tables:
get_non_complying_sessions(),
get_removed_sessions(),
get_sessions_summary()
get_epochs_summary(example_epochs)get_epochs_summary(example_epochs)
Get non-complying sessions (i.e. where there is more than one session on the same day)
get_non_complying_sessions(sessions)get_non_complying_sessions(sessions)
sessions |
The sessions dataframe |
This function uses columns:
night
The sessions dataframe with only the sessions that are non-complying
Other data tables:
get_epochs_summary(),
get_removed_sessions(),
get_sessions_summary()
duplicate_sessions <- get_non_complying_sessions(example_sessions)duplicate_sessions <- get_non_complying_sessions(example_sessions)
Get a table of sessions that were removed during filtering
get_removed_sessions(sessions, filtered_sessions)get_removed_sessions(sessions, filtered_sessions)
sessions |
The original sessions dataframe |
filtered_sessions |
The filtered sessions dataframe |
This function uses columns:
id
sleep_period
The sessions dataframe with only the sessions that were removed during filtering
Other data tables:
get_epochs_summary(),
get_non_complying_sessions(),
get_sessions_summary()
filtered_sessions <- set_session_start_time_range(example_sessions, "22:00", "06:00") removed_sessions <- get_removed_sessions(example_sessions, filtered_sessions)filtered_sessions <- set_session_start_time_range(example_sessions, "22:00", "06:00") removed_sessions <- get_removed_sessions(example_sessions, filtered_sessions)
This function retrieves the standard column names for sessions data. If the column names are not set as an attribute, it attempts to infer them from a list of common column names.
get_session_colnames(sessions)get_session_colnames(sessions)
sessions |
A data frame containing sessions data |
A named list of column names
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_epoch_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
get_session_colnames(example_sessions)get_session_colnames(example_sessions)
Summarise session information, including the number of sessions, mean session length, mean time at sleep onset and wakeup, subject and device ID.
get_sessions_summary(sessions)get_sessions_summary(sessions)
sessions |
The sessions dataframe. |
This function uses columns:
time_at_sleep_onset
time_at_wakeup
time_in_bed
sleep_period
A single-row dataframe summarizing session information.
get_epochs_summary() to summarise epoch information.
Other data tables:
get_epochs_summary(),
get_non_complying_sessions(),
get_removed_sessions()
get_sessions_summary(example_sessions)get_sessions_summary(example_sessions)
This function returns the number of specified time units (seconds, minutes or hours) in a day.
get_time_per_day(unit = "second")get_time_per_day(unit = "second")
unit |
The unit of time. Can be "second", "minute", or "hour". Default is "second". |
The number of time units in a day (numeric)
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
is_iso8601_datetime(),
set_colnames(),
set_data_type()
get_time_per_day("hour")get_time_per_day("hour")
The function creates a new column night that groups the epochs by night.
Timepoints before 12 PM are considered part of the previous night.
group_epochs_by_night(epochs)group_epochs_by_night(epochs)
epochs |
The epochs dataframe |
This function uses columns:
timestamp
The epochs dataframe with the night column added
group_sessions_by_night() to group session data by night.
Other time processing:
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
epochs <- group_epochs_by_night(example_epochs)epochs <- group_epochs_by_night(example_epochs)
The function creates a new column night that groups the sessions by night depending on their start time.
Sessions that start before 12 PM are considered part of the previous night.
group_sessions_by_night(sessions)group_sessions_by_night(sessions)
sessions |
The sessions dataframe |
This function uses columns:
session_start
The sessions dataframe with the night column added
group_epochs_by_night() to group epoch data by night.
Other time processing:
group_epochs_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
sessions <- group_sessions_by_night(example_sessions)sessions <- group_sessions_by_night(example_sessions)
This function calculates the Interdaily Stability (IS) metric from a binary awake/asleep variable
interdaily_stability(epochs)interdaily_stability(epochs)
epochs |
The epochs data frame |
This function uses columns:
timestamp
is_asleep
The Interdaily Stability (IS) value
Other sleep metrics:
chronotype(),
composite_phase_deviation(),
sleep_regularity_index(),
social_jet_lag()
interdaily_stability(example_epochs)interdaily_stability(example_epochs)
This function checks if all non-missing values in a column are valid ISO 8601 datetime strings.
is_iso8601_datetime(x)is_iso8601_datetime(x)
x |
A vector of character strings |
TRUE if all non-missing values are valid ISO 8601 datetime strings, FALSE otherwise
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
set_colnames(),
set_data_type()
is_iso8601_datetime(c("2026-01-01T14:10"))is_iso8601_datetime(c("2026-01-01T14:10"))
Load session or epoch data in batch mode
load_batch( folder_path = NULL, file_list = NULL, file_names = NULL, pattern = NULL, type = "sessions" )load_batch( folder_path = NULL, file_list = NULL, file_names = NULL, pattern = NULL, type = "sessions" )
folder_path |
The path to the folder containing session files (do not use with file_list) |
file_list |
The list of file paths to load (do not use with folder_path) |
file_names |
An optional vector of file names corresponding to the files in file_list |
pattern |
An optional pattern to filter files in the folder |
type |
The type of data to load: "sessions" or "epochs" |
A dataframe containing the combined session data from all matching files in the folder
Other data loading:
load_epochs(),
load_sessions(),
read_edf_epochs(),
read_edf_sessions()
tf1 <- tempfile(fileext = ".csv") tf2 <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf1, row.names = FALSE) utils::write.csv(data.frame(id = 1), tf2, row.names = FALSE) load_batch(file_list = c(tf1, tf2))tf1 <- tempfile(fileext = ".csv") tf2 <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf1, row.names = FALSE) utils::write.csv(data.frame(id = 1), tf2, row.names = FALSE) load_batch(file_list = c(tf1, tf2))
Load epoch data
load_epochs(epochs_file, file_name = NULL)load_epochs(epochs_file, file_name = NULL)
epochs_file |
The path to the epochs file |
file_name |
An optional file name to be recorded in the epochs table |
The function loads the epoch data from a file and groups the epochs by night. Supported formats: CSV, Excel, EDF.
A dataframe containing the epoch data
Other data loading:
load_batch(),
load_sessions(),
read_edf_epochs(),
read_edf_sessions()
tf <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf, row.names = FALSE) load_epochs(tf)tf <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf, row.names = FALSE) load_epochs(tf)
Load session data
load_sessions(sessions_file)load_sessions(sessions_file)
sessions_file |
The path to the sessions file |
The function loads the session data from a file Supported formats: CSV, Excel, EDF.
A dataframe containing the session data
Other data loading:
load_batch(),
load_epochs(),
read_edf_epochs(),
read_edf_sessions()
tf <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf, row.names = FALSE) load_sessions(tf)tf <- tempfile(fileext = ".csv") utils::write.csv(data.frame(id = 1), tf, row.names = FALSE) load_sessions(tf)
This function calculates the maximum time from a vector of time strings in the format "YYYY-MM-DD HH:MM:SS". It considers a time window from 12pm to 12pm the next day, so 11:00 is considered later than 13:00.
max_time(time_vector)max_time(time_vector)
time_vector |
A vector of time strings in the format "YYYY-MM-DD HH:MM:SS". |
A string representing the maximum time in the format "HH:MM".
min_time() to calculate the minimum time in the same format.
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
max_time(c("2025-04-08 23:00:00", "2025-04-09 01:00:00", "2025-04-09 02:30:00"))max_time(c("2025-04-08 23:00:00", "2025-04-09 01:00:00", "2025-04-09 02:30:00"))
This function calculates the mean time from a vector of time strings in the format "YYYY-MM-DD HH:MM:SS".
mean_time(time_vector, unit = "HH:MM")mean_time(time_vector, unit = "HH:MM")
time_vector |
A vector of time strings in format "YYYY-MM-DD HH:MM:SS", "HH:MM:SS" or "HH:MM". |
unit |
The unit of time for the result. Can be "HH:MM" (default), "hour", "minute" or "second". |
A string representing the mean time in the format "HH:MM".
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
# Use on a vector of time strings representing full dates time_vector <- c("2025-04-08 23:00:00", "2025-04-09 01:00:00") mean_time(time_vector) # Use on time-only strings time_vector <- c("22:56", "01:32") mean_time(time_vector) # Use on a dataframe column mean_time(example_sessions$time_at_sleep_onset)# Use on a vector of time strings representing full dates time_vector <- c("2025-04-08 23:00:00", "2025-04-09 01:00:00") mean_time(time_vector) # Use on time-only strings time_vector <- c("22:56", "01:32") mean_time(time_vector) # Use on a dataframe column mean_time(example_sessions$time_at_sleep_onset)
This function calculates the minimum time from a vector of time strings in the format "YYYY-MM-DD HH:MM:SS". It considers a time window from 12pm to 12pm the next day, so 11:00 is considered later than 13:00.
min_time(time_vector)min_time(time_vector)
time_vector |
A vector of time strings in the format "YYYY-MM-DD HH:MM:SS". |
A string representing the minimum time in the format "HH:MM".
max_time() to calculate the maximum time in the same format.
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
min_time(c("2025-04-08 23:00:00", "2025-04-09 01:00:00", "2025-04-09 02:30:00"))min_time(c("2025-04-08 23:00:00", "2025-04-09 01:00:00", "2025-04-09 02:30:00"))
This function launches the nocturn app, a Shiny application for visualizing and analyzing sleep data.
nocturn()nocturn()
No return value, called for side-effects
if(interactive()){nocturn()}if(interactive()){nocturn()}
This function parses a vector of date strings into Date objects. All formats containing year, month, and day information are supported.
parse_date(date_vector)parse_date(date_vector)
date_vector |
A vector of date strings |
A vector of Date objects
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
parse_date("2026-01-02T14:33:09")parse_date("2026-01-02T14:33:09")
This function parses a vector of time strings into POSIXct objects. Supported formats include "YYYY-MM-DD HH:MM:SS", "YYYY-MM-DD HH:MM", "HH:MM:SS", and "HH:MM". Timezone information is ignored.
parse_time(time_vector)parse_time(time_vector)
time_vector |
A vector of time strings |
A vector of POSIXct objects
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
parse_time("2026-01-01T14:34:09")parse_time("2026-01-01T14:34:09")
Plot bedtimes and waketimes
plot_bedtimes_waketimes(sessions, groupby = "night", color_by = "default")plot_bedtimes_waketimes(sessions, groupby = "night", color_by = "default")
sessions |
The sessions dataframe |
groupby |
The grouping variable for the plot. Can be "night", "workday", or "weekday". |
color_by |
The variable to color the bars by. Can be "default" or any other column name in the sessions dataframe. Note that if color_by is anything else than "default", groupby will be set to "night". |
This function uses columns:
night
time_at_sleep_onset
time_at_wakeup
is_workday
A ggplot graph showing the bedtimes and waketimes
plot_bedtimes_waketimes(example_sessions)plot_bedtimes_waketimes(example_sessions)
Plot Hypnogram
plot_hypnogram(epochs)plot_hypnogram(epochs)
epochs |
The epochs dataframe |
This function uses columns:
timestamp
sleep_stage
A ggplot object showing the hypnogram as bars
Other plot epochs:
plot_sleep_spiral(),
plot_timeseries()
plot_hypnogram(example_epochs)plot_hypnogram(example_epochs)
This function creates a bubble plot of sleep sessions, where the size and colour of the bubbles represents the sleep duration.
plot_sleep_bubbles(sessions, color_by = "default", bubble_size = 10)plot_sleep_bubbles(sessions, color_by = "default", bubble_size = 10)
sessions |
The sessions dataframe. |
color_by |
The variable to color the bubbles by. Can be "default" or any other column name in the sessions dataframe. |
bubble_size |
The size of the bubbles. Default is 10. |
This function uses columns:
sleep_period
night
A ggplot object containing the sleep bubbles graph.
Other plot sessions:
plot_sleep_clock(),
plot_timeseries_sessions()
plot_sleep_bubbles(example_sessions)plot_sleep_bubbles(example_sessions)
Plot Sleep Clock
plot_sleep_clock(sessions, color_by = "default")plot_sleep_clock(sessions, color_by = "default")
sessions |
The sessions dataframe |
color_by |
The variable to color the segments by. Can be "default" or any other column name in the sessions dataframe. |
This function uses columns:
time_at_sleep_onset
time_at_wakeup
night
A ggplot object showing the sleep clock
Other plot sessions:
plot_sleep_bubbles(),
plot_timeseries_sessions()
plot_sleep_clock(example_sessions)plot_sleep_clock(example_sessions)
Plot Sleep Spiral
plot_sleep_spiral(epochs, color_by = "default")plot_sleep_spiral(epochs, color_by = "default")
epochs |
The epochs dataframe |
color_by |
The variable to color the spiral by. Can be "default" or any other column name in the epochs dataframe. |
This function uses columns:
timestamp
is_asleep
A ggplot object showing the sleep spiral
Other plot epochs:
plot_hypnogram(),
plot_timeseries()
plot_sleep_spiral(example_epochs)plot_sleep_spiral(example_epochs)
Plot epoch time series data for a given variable
plot_timeseries(epochs, variable, color_by = "default", exclude_zero = FALSE)plot_timeseries(epochs, variable, color_by = "default", exclude_zero = FALSE)
epochs |
The epochs dataframe |
variable |
The variable to plot (e.g., "temperature_ambient_mean") |
color_by |
The variable to color the points by. Can be "default" or any other column name in the epochs dataframe. |
exclude_zero |
Logical, whether to exclude zero values from the plot (default: FALSE) |
This function uses columns:
timestamp
night
A ggplot object
plot_timeseries_sessions() to plot session data.
Other plot epochs:
plot_hypnogram(),
plot_sleep_spiral()
plot_timeseries(example_epochs, variable="signal_quality_mean")plot_timeseries(example_epochs, variable="signal_quality_mean")
Plot session time series data for a given variable
plot_timeseries_sessions( sessions, variable, color_by = "default", exclude_zero = FALSE )plot_timeseries_sessions( sessions, variable, color_by = "default", exclude_zero = FALSE )
sessions |
The sessions dataframe |
variable |
The variable to plot (e.g., "time_at_sleep_onset") |
color_by |
The variable to color the points by. Can be "default" or any other column name in the sessions dataframe. |
exclude_zero |
Logical, whether to exclude zero values from the plot (default: FALSE) |
This function uses columns:
night
A ggplot object
plot_timeseries() to plot epoch data.
Other plot sessions:
plot_sleep_bubbles(),
plot_sleep_clock()
plot_timeseries_sessions(example_sessions, variable="time_at_midsleep")plot_timeseries_sessions(example_sessions, variable="time_at_midsleep")
Read EDF Epochs
read_edf_epochs(file)read_edf_epochs(file)
file |
The path to the EDF file |
The function reads the signals of the EDF file to extract epoch information. It must contain a column for timestamps and a column for sleep stage annotations.
A dataframe containing the epoch data extracted from the EDF file signals
Other data loading:
load_batch(),
load_epochs(),
load_sessions(),
read_edf_sessions()
edf <- system.file("extdata", "mini.edf", package = "nocturn") read_edf_epochs(edf)edf <- system.file("extdata", "mini.edf", package = "nocturn") read_edf_epochs(edf)
Read EDF Sessions
read_edf_sessions(file)read_edf_sessions(file)
file |
The path to the EDF file |
The function reads the header of the EDF file to extract session information such as start time, duration, and calculates end time and midsleep time.
A dataframe containing the session data extracted from the EDF file header
Other data loading:
load_batch(),
load_epochs(),
load_sessions(),
read_edf_epochs()
edf <- system.file("extdata", "mini.edf", package = "nocturn") read_edf_sessions(edf)edf <- system.file("extdata", "mini.edf", package = "nocturn") read_edf_sessions(edf)
Remove sessions with no sleep
remove_sessions_no_sleep(sessions, return_mask = FALSE)remove_sessions_no_sleep(sessions, return_mask = FALSE)
sessions |
The sessions dataframe |
return_mask |
If TRUE, returns a logical vector indicating which sessions have a sleep period greater than 0 |
This function uses columns:
sleep_period
The sessions dataframe with only the sessions that have a sleep period greater than 0, or a logical vector if return_mask is TRUE
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- remove_sessions_no_sleep(example_sessions)filtered_sessions <- remove_sessions_no_sleep(example_sessions)
This function calculates the standard deviation of a vector of time strings, accounting for the circular nature of time (e.g., 23:59 is close to 00:00).
sd_time(time_vector, unit = "hour")sd_time(time_vector, unit = "hour")
time_vector |
A vector of time strings in format "YYYY-MM-DD HH:MM:SS", "HH:MM:SS" or "HH:MM". |
unit |
The unit of time for the result. Can be "second", "minute", or "hour". Default is "hour". |
A numeric value representing the standard deviation in the specified unit.
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours(),
update_date()
sd_time(c("23:59", "00:01"))sd_time(c("23:59", "00:01"))
Select devices by ID
select_devices(sessions, device_ids, return_mask = FALSE)select_devices(sessions, device_ids, return_mask = FALSE)
sessions |
The sessions dataframe |
device_ids |
The device IDs to select |
return_mask |
If TRUE, returns a logical vector indicating which sessions were recorded by the specified devices |
This function uses columns:
device_id
The sessions dataframe with only the sessions recorded by the specified devices, or a logical vector if return_mask is TRUE
select_subjects() to select sessions by subject ID.
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- select_devices(example_sessions, c("VTGVSRTHCA"))filtered_sessions <- select_devices(example_sessions, c("VTGVSRTHCA"))
Select subjects by ID
select_subjects(sessions, subject_ids, return_mask = FALSE)select_subjects(sessions, subject_ids, return_mask = FALSE)
sessions |
The sessions dataframe |
subject_ids |
The subject IDs to select |
return_mask |
If TRUE, returns a logical vector indicating which sessions belong to the specified subjects
|
This function uses columns:
The sessions dataframe with only the sessions that belong to the specified subjects, or a logical vector if return_mask is TRUE
select_devices() to select sessions by device ID.
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- select_subjects(example_sessions, c("sub_01JNDH3Z5NP0PSV82NFBGPV31X"))filtered_sessions <- select_subjects(example_sessions, c("sub_01JNDH3Z5NP0PSV82NFBGPV31X"))
This function updates the "col" attribute for a dataframe, overwriting existing column names with the ones provided.
set_colnames(df, col)set_colnames(df, col)
df |
A data frame |
col |
A named list of column names |
The data frame with updated "col" attribute
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_data_type()
sessions <- set_colnames( example_sessions, list(night = "calendar_date", sleep_period = "duration_sleep") )sessions <- set_colnames( example_sessions, list(night = "calendar_date", sleep_period = "duration_sleep") )
This function sets the "type" attribute for a data frame to indicate whether it contains session or epoch data.
set_data_type(data, type)set_data_type(data, type)
data |
A data frame containing either sessions or epochs data |
type |
A string indicating the type of data (e.g. "sessions" or "epochs") |
The data frame with updated "type" attribute
Other internal:
check_suggests(),
get_col(),
get_colnames(),
get_epoch_colnames(),
get_session_colnames(),
get_time_per_day(),
is_iso8601_datetime(),
set_colnames()
set_data_type(example_sessions, "sessions")set_data_type(example_sessions, "sessions")
Set minimum sleep period
set_min_sleep_period(sessions, min_sleep_period, return_mask = FALSE)set_min_sleep_period(sessions, min_sleep_period, return_mask = FALSE)
sessions |
The sessions dataframe |
min_sleep_period |
The minimum sleep period in hours |
return_mask |
If TRUE, return a logical vector indicating which sessions meet the minimum sleep period requirement |
This function uses columns:
sleep_period
The sessions dataframe with only the sessions that meet the minimum sleep period requirement, or a logical vector if return_mask is TRUE
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_time_in_bed(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- set_min_sleep_period(example_sessions, 2)filtered_sessions <- set_min_sleep_period(example_sessions, 2)
Set minimum time in bed
set_min_time_in_bed(sessions, min_time_in_bed, return_mask = FALSE)set_min_time_in_bed(sessions, min_time_in_bed, return_mask = FALSE)
sessions |
The sessions dataframe |
min_time_in_bed |
The minimum time in bed in hours |
return_mask |
If TRUE, return a logical vector indicating which sessions meet the minimum time in bed requirement |
This function uses columns:
time_in_bed
The sessions dataframe with only the sessions that meet the minimum time in bed requirement, or a logical vector if return_mask is TRUE
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_session_sleep_onset_range(),
set_session_start_time_range()
filtered_sessions <- set_min_time_in_bed(example_sessions, 2)filtered_sessions <- set_min_time_in_bed(example_sessions, 2)
Set sleep onset time range
set_session_sleep_onset_range( sessions, from_time, to_time, return_mask = FALSE )set_session_sleep_onset_range( sessions, from_time, to_time, return_mask = FALSE )
sessions |
The sessions dataframe |
from_time |
Include sessions where sleep started after this time (in format HH:MM) |
to_time |
Include sessions where sleep started before this time (in format HH:MM) |
return_mask |
If TRUE, returns a logical vector indicating which sessions meet the sleep onset time range requirement |
This function uses columns:
time_at_sleep_onset
The sessions dataframe with only the sessions where sleep started within the specified time range,
or a logical vector if return_mask is TRUE
set_session_start_time_range() to filter sessions based on start time.
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_start_time_range()
filtered_sessions <- set_session_sleep_onset_range(example_sessions, "22:00", "06:00")filtered_sessions <- set_session_sleep_onset_range(example_sessions, "22:00", "06:00")
Set session start time range
set_session_start_time_range(sessions, from_time, to_time, return_mask = FALSE)set_session_start_time_range(sessions, from_time, to_time, return_mask = FALSE)
sessions |
The sessions dataframe |
from_time |
Include sessions that started after this time (in format HH:MM) |
to_time |
Include sessions that started before this time (in format HH:MM) |
return_mask |
If TRUE, returns a logical vector indicating which sessions meet the time range requirement |
This function uses columns:
session_start
The sessions dataframe with only the sessions that started within the specified time range, or a logical vector if return_mask is TRUE
set_session_sleep_onset_range() to filter sessions based on sleep onset time.
Other filtering:
filter_by_age_range(),
filter_by_night_range(),
filter_by_sex(),
filter_epochs_from_sessions(),
remove_sessions_no_sleep(),
select_devices(),
select_subjects(),
set_min_sleep_period(),
set_min_time_in_bed(),
set_session_sleep_onset_range()
filtered_sessions <- set_session_start_time_range(example_sessions, "22:00", "06:00")filtered_sessions <- set_session_start_time_range(example_sessions, "22:00", "06:00")
This function shifts times so that the day starts at 12 PM. This is useful for plotting night data
shift_times_by_12h(times)shift_times_by_12h(times)
times |
A vector of times in POSIXct format, character convertible to POSIXct, or numerical (in hours). |
A vector of times in POSIXct format (or numerical if numerical provided as input) shifted to start at 12 PM
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
time_diff(),
time_to_hours(),
update_date()
# Shift a vector of times in HH:MM format shift_times_by_12h(c("02:30", "16:00")) #> "14:30" "04:00" # Shift times in YYYY-MM-DD HH:MM:SS format shift_times_by_12h(c("2025-04-08 23:00:00", "2025-04-09 01:00:00")) #> "2025-04-08 11:00" "2025-04-09 13:00" # Shift sessions start times to start at 12 PM shifted_times <- shift_times_by_12h(example_sessions$session_start) # Use dplyr::mutate to dicrectly add the shifted times to a dataframe epochs <- example_epochs |> dplyr::mutate(shifted_time = shift_times_by_12h(timestamp))# Shift a vector of times in HH:MM format shift_times_by_12h(c("02:30", "16:00")) #> "14:30" "04:00" # Shift times in YYYY-MM-DD HH:MM:SS format shift_times_by_12h(c("2025-04-08 23:00:00", "2025-04-09 01:00:00")) #> "2025-04-08 11:00" "2025-04-09 13:00" # Shift sessions start times to start at 12 PM shifted_times <- shift_times_by_12h(example_sessions$session_start) # Use dplyr::mutate to dicrectly add the shifted times to a dataframe epochs <- example_epochs |> dplyr::mutate(shifted_time = shift_times_by_12h(timestamp))
The Sleep Regularity Index (SRI) is a measure of the regularity of sleep patterns. It is calculated as the percentage of epochs where the sleep state remains the same after 24 hours.
sleep_regularity_index(epochs)sleep_regularity_index(epochs)
epochs |
The epochs data frame |
This function uses columns:
timestamp
is_asleep
The Sleep Regularity Index (SRI) value
Other sleep metrics:
chronotype(),
composite_phase_deviation(),
interdaily_stability(),
social_jet_lag()
sleep_regularity_index(example_epochs)sleep_regularity_index(example_epochs)
This function generates a sleep report in PDF format using an SVG template. It is designed to work with Somnofy data. Other data types may be supported in the future.
sleep_report(sessions, title = "", output_file = "Sleep_report.pdf")sleep_report(sessions, title = "", output_file = "Sleep_report.pdf")
sessions |
The sessions dataframe |
title |
The title of the report. Default is an empty string. |
output_file |
Path for the output PDF. Default is "Sleep_report.pdf" |
This function uses columns:
night
time_at_sleep_onset
time_at_wakeup
time_at_midsleep
sleep_onset_latency
sleep_period
time_in_bed
No return value. Called for side-effects
sleep_report(example_sessions)sleep_report(example_sessions)
Plot boxplots for sleep onset, midsleep, and wakeup times
sleeptimes_boxplot(sessions, circular = FALSE)sleeptimes_boxplot(sessions, circular = FALSE)
sessions |
The sessions dataframe |
circular |
Whether to output a circular plot (default FALSE) |
This function uses columns:
time_at_sleep_onset
time_at_wakeup
time_at_midsleep
A ggplot object with three horizontal boxplots (onset, midsleep, wakeup)
sleeptimes_boxplot(example_sessions)sleeptimes_boxplot(example_sessions)
Plot density curves for sleep onset, midsleep, and wakeup times with a dashed line showing the median
sleeptimes_density(sessions, adjust = 1, circular = FALSE)sleeptimes_density(sessions, adjust = 1, circular = FALSE)
sessions |
The sessions dataframe |
adjust |
The bandwidth adjustment for the density estimate (default 1) |
circular |
Whether to output a circular plot (default FALSE) |
This function uses columns:
time_at_sleep_onset
time_at_wakeup
time_at_midsleep
A ggplot object with three overlaid density curves (sleep onset, midsleep, wakeup)
sleeptimes_density(example_sessions)sleeptimes_density(example_sessions)
Plot histograms for sleep onset, midsleep, and wakeup times
sleeptimes_histogram(sessions, binwidth = 0.25, circular = FALSE)sleeptimes_histogram(sessions, binwidth = 0.25, circular = FALSE)
sessions |
The sessions dataframe |
binwidth |
The width of the bins for the histogram (default 0.25) |
circular |
Whether to output a circular plot (default FALSE) |
This function uses columns:
time_at_sleep_onset
time_at_wakeup
time_at_midsleep
A ggplot object with three overlaid histograms (sleep onset, midsleep, wakeup)
sleeptimes_histogram(example_sessions)sleeptimes_histogram(example_sessions)
This function returns the time from t1 to t2, always moving forward on the clock. For example, from 07:00 to 22:00 is 15 hours, from 22:00 to 07:00 is 9 hours.
time_diff(t1, t2, unit = "hour")time_diff(t1, t2, unit = "hour")
t1 |
First time (character, POSIXct, or numeric hour) |
t2 |
Second time (character, POSIXct, or numeric hour) |
unit |
The unit of time. Can be "second", "minute", or "hour". Default is "hour". |
The forward difference in the specified unit (numeric, always positive, 0 <= x < 24)
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_to_hours(),
update_date()
time_diff("07:00", "22:00") # 15 time_diff("22:00", "07:00") # 9 time_diff("07:00", "22:00", unit = "minute") # 540time_diff("07:00", "22:00") # 15 time_diff("22:00", "07:00") # 9 time_diff("07:00", "22:00", unit = "minute") # 540
This function converts a vector of time strings or POSIXct objects to numeric hours.
time_to_hours(time_vector)time_to_hours(time_vector)
time_vector |
A vector of time strings |
See parse_time() for supported time formats.
A numeric vector representing the time in hours
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
update_date()
time_to_hours(c("2026-10-12T14:20:09"))time_to_hours(c("2026-10-12T14:20:09"))
This function updates the date component of a POSIXct time object while preserving the time component.
update_date(time, date)update_date(time, date)
time |
A POSIXct time object or a character string convertible to POSIXct |
date |
A Date object or a character string convertible to Date |
A POSIXct time object with the updated date
Other time processing:
group_epochs_by_night(),
group_sessions_by_night(),
max_time(),
mean_time(),
min_time(),
parse_date(),
parse_time(),
sd_time(),
shift_times_by_12h(),
time_diff(),
time_to_hours()
update_date("2026-01-01T14:09:09", "0000-01-01")update_date("2026-01-01T14:09:09", "0000-01-01")
Calculate Social Jet Lag
Description
This function calculates the Social Jet Lag (SJL) metric as the difference in mid-sleep times between workdays and free days.
Usage
Arguments
sessionsThe sessions data frame
Details
This function uses columns:
time_at_midsleepis_workdayValue
The Social Jet Lag (SJL) value in hours
See Also
Other sleep metrics:
chronotype(),composite_phase_deviation(),interdaily_stability(),sleep_regularity_index()Examples