| Title: | Wearable Recording Processor for Time Shift Adjustment and Data Analysis |
|---|---|
| Description: | Cross-continental travel and local practices of daylight saving time can induce time shift. When left unadjusted, it can lead to biases in interpreting wearable measures. This research tool streamlines data processing and analysis (e.g., cosinor analysis, circularized kernel density estimation) for longitudinal recordings. Together with additional features such as exporting daily wearable measures and creating visual reports, it aims to facilitate research on longitudinal wearable measurements. To learn its application, please refer to the provided vignettes for a brief tutorial. This tool is developed based on the methodology detailed in: Varesco, G. Yao, C. W., Dubé, E., Simonelli, G., Bieuzen, F., (2024) <doi:10.1113/ep092195>. |
| Authors: | C. William Yao [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-7234-7375>), Giorgio Varesco [aut, ctb] (ORCID: <https://orcid.org/0000-0001-9385-6972>), François Bieuzen [aut, ctb] (ORCID: <https://orcid.org/0000-0002-9690-9168>), Guido Simonelli [aut, ctb, fnd] (ORCID: <https://orcid.org/0000-0002-5400-319X>) |
| Maintainer: | C. William Yao <[email protected]> |
| License: | AGPL (>= 3) |
| Version: | 0.2.2 |
| Built: | 2026-09-17 09:05:50 UTC |
| Source: | https://github.com/cwy20030/ActiGlobe |
'Act2Daily' is used to split the actigraphy recording by the recording dates stored in Bdf (a BriefSum object).
Act2Daily( df, Bdf, TUnit = "hour", VAct = NULL, VTm = NULL, Incomplete = FALSE, Travel = TRUE )Act2Daily( df, Bdf, TUnit = "hour", VAct = NULL, VTm = NULL, Incomplete = FALSE, Travel = TRUE )
df |
A data.frame of raw actigraphy recording. Both time and activity
count should be included in the |
Bdf |
A |
TUnit |
Character; time–unit for the x–axis of each day's timeline. Must be one of "day", "hour", "minute" or "second". Default is "hour". |
VAct |
Optional character. Name of the activity column in |
VTm |
Optional character. Name of the date.time index column in
|
Incomplete |
Logical; if TRUE, days flagged 'Incomplete Recording' (i.e. <24 h) are retained in the data list with recordings segmented by day. Default = FALSE (these days are removed). |
Travel |
Logical; if TRUE, days flagged 'Travel' are retained although some data points from an earlier adjacent calendar day may be duplicated (a warning is issued). If FALSE, travel days and the day before/after are excluded. Default = TRUE. |
Transforms a continuous actigraphy time-series into a day-by-day
list of aligned epoch and produces a fully annotated data frame. Based on
the summary table generated by either BriefSum or
TAdjust, it re-organize and segment the raw recording data by
each day. The function is designed to process incomplete recordings while
accounting for travel and daylight-saving adjustments. All labels contained
in the summary table (i.e., Bdf) will be assigned to the corresponding data
points. This workflow ensures that each day's recording is bounded by its
calendar date while accounts for travel–induced overlaps, and clearly
documents any incomplete or unallocated points.
A data list that includes the adjusted recordings both in long format and as a nested list by day.
When you cross into a time zone with a larger UTC offset (e.g., Montreal
to Taipei ), it will generate a small overlap of
epochs between the day before travel and the day labeled "Travel Day" in the
"Daily_df". Conversely,when you move into a time zone with a smaller UTC
offset, a brief gap appears on "Travel Day", with labeling - "Unallocated",
which represents "time lose".
## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Lets extract the quick summary of the recording Bdf <- BdfList$Bdf ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] df <- BdfList$df # Segment Data by Day dfList <- Act2Daily ( df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time", Incomplete = TRUE, Travel = TRUE ) str (dfList) ### Look at the output structure View (dfList) ## End(Not run)## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Lets extract the quick summary of the recording Bdf <- BdfList$Bdf ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] df <- BdfList$df # Segment Data by Day dfList <- Act2Daily ( df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time", Incomplete = TRUE, Travel = TRUE ) str (dfList) ### Look at the output structure View (dfList) ## End(Not run)
Computes standard errors and confidence intervals for cosinor and post-hoc parameters via non-parametric bootstrap
boot.seci(object, ci_level = 0.95, n = 500, digits = 2)boot.seci(object, ci_level = 0.95, n = 500, digits = 2)
object |
A fitted 'CosinorM' or 'CosinorM.KDE' model object. |
ci_level |
Numeric scaler. The threshold for the confidence interval. Default: 0.95 |
n |
Numeric scaler. Numbers of bootstraps required to estimate the standard errors and confidence intervals. Default: 500 |
digits |
Numeric scaler. Integer indicating the number of decimal places (round) to be used. Default: 2 |
A data.frame with one row per cosinor coefficient and columns:
Estimate: Mean of bootstrap coefficient values.
Std Error: Bootstrap standard deviation of each coefficient across n resamples.
t value: Ratio of the observed estimate to its bootstrap standard error, analogous to a signal-to-noise measure:
lower CI label: Percentile lower bound at ,
where .
upper CI label: Percentile upper bound at .
## Not run: # Import data FlyEast BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-27") # Multicomponent Cosinor Model fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = c (12, 24), method = "OLS" ) # inspect coefficients boot.seci ( object = fit, ci_level = 0.95, n = 500 ) # Gaussian Kernel Density Estimation fit2 <- CosinorM.KDE ( time = df$Time, activity = df$Activity ) # inspect coefficients boot.seci ( object = fit2, ci_level = 0.95, n = 500 ) ## End(Not run)## Not run: # Import data FlyEast BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-27") # Multicomponent Cosinor Model fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = c (12, 24), method = "OLS" ) # inspect coefficients boot.seci ( object = fit, ci_level = 0.95, n = 500 ) # Gaussian Kernel Density Estimation fit2 <- CosinorM.KDE ( time = df$Time, activity = df$Activity ) # inspect coefficients boot.seci ( object = fit2, ci_level = 0.95, n = 500 ) ## End(Not run)
'BriefSum()' is a function that summarizes the actigraphy recording by day. It generates a data.frame where each row holds all metadata for one recording day: the calendar date, time–zone code, epoch length (seconds), UTC offset, daylight–saving flag, cumulative start/end seconds from midnight, recording start/end times (HH:MM:SS), any warning labels (e.g. 'Travel', 'Incomplete Recording'), an exclusion flag, and the expected number of epochs for a full day.
BriefSum(df, SR, Start, TZ = "local")BriefSum(df, SR, Start, TZ = "local")
df |
A data.frame of raw actigraphy recording. Both time and activity
count should be included in the |
SR |
The sampling rate of the actigraphy (unit at Hz). Note that Hz should be equal to or less than 1. |
Start |
The starting date and time of the recording in the format
as "2021-03-05 18:31:03". See |
TZ |
The time zone when the recording started. (default = "local", which means user's local time zone) |
A named list with two elements:
Bdf A data.frame containing brief summary information of each recording day. Columns include:
Date calendar date (YYYY-MM-DD)
Epoch epoch length in seconds
UTC dominant UTC offset string (e.g., "UTC+02:00")
TZ_code time zone code (e.g., "EST")
Daylight_Saving logical flag indicating DST for the day
Recording_Start earliest recorded time for the day (HH:MM:SS)
Recording_End latest recorded time for the day (HH:MM:SS)
GL_Offset numeric offset returned by DST2GL for the
day
nDataPoints number of epochs observed for the day
Cumulative_Start_Second cumulative start second from midnight for the day's first epoch
Cumulative_End_Second cumulative end second from midnight for the day's last epoch
Excluded logical flag; TRUE if the day is excluded (e.g., incomplete)
Warning character; warning label when applicable (e.g., "Incomplete Recording", "Time Change")
df The original input df augmented with additional columns (class ActiGlobe, data.frame):
DateTime POSIXct timestamp for each epoch (tz = TZ)
Date date string (YYYY-MM-DD)
Time time string (HH:MM:SS)
UTC UTC offset string for each epoch
DaylightSaving logical flag per epoch
nPoint cumulative epoch index
The function returns a list with both Bdf df = df) and sets classes c("ActiGlobe","data.frame") on both returned data.frames.
# Import data data (FlyEast) BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-19 13:45:00" ) str (BdfList) # View(BdfList) ## install library "zeallot" ## library(zeallot) ## c(Bdf, df) %<-% ## BriefSum(df = FlyEast, ## SR = 1/60, ## Start = "2017-10-24 13:45:00")# Import data data (FlyEast) BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-19 13:45:00" ) str (BdfList) # View(BdfList) ## install library "zeallot" ## library(zeallot) ## c(Bdf, df) %<-% ## BriefSum(df = FlyEast, ## SR = 1/60, ## Start = "2017-10-24 13:45:00")
Fit a cosine-based harmonic linear regression on circular time (hours of day)
CosinorM( time, activity, tau, method = "OLS", arctan2 = TRUE, type = "HC3", dilute = FALSE )CosinorM( time, activity, tau, method = "OLS", arctan2 = TRUE, type = "HC3", dilute = FALSE )
time |
Numeric vector of time coordinates for each data point |
activity |
Numeric vector of activity counts from an actigraphy device |
tau |
Numeric scalar or vector for the assumed circadian period. Default is 24 for single-phase; multiple phases can be supplied via [c()] |
method |
Character string specifying estimation method
|
arctan2 |
Logical; if TRUE (default) acrophase is computed with
|
type |
Character string passed to |
dilute |
Logical;
|
The 'Cosinor' model is a cosine-based harmonic regression used to estimate circadian rhythm parameters.
Single-phase equation:
: MESOR (mid-line estimating statistic of rhythm), the
intercept
: Amplitude, peak deviation from M
: Time coordinate within the cycle
: The assumed period length
: Acrophase (time-of-peak), computed from fitted sine and
cosine coefficients
Note that because the model is parameterized with a negative phase inside the cosine, this means the the derived peak time from acrophase corresponds to the peak time forward from midnight (not backward). In other words, the when the acrophase is positive, it means the peak activity time occurs after midnight and vice versa.
Linearized form:
, estimated coefficient for the cosine
term
, cosine-transformed time
, estimated coefficient for the sine
term
, sine-transformed time
: error term
Model parameters are estimated by minimizing the residual sum of squares:
By default, lm fits this via QR decomposition.
Acrophase interpretation:
is derived from
Note,
can be converted to clock time to identify the peak
activity time AFTER midnight.
if the model is not a mono-phase (i.e., more than one ),
there will be number of peaks within a day.
Amplitude estimation:
Amplitude is calculated from fitted sine and cosine coefficients as:
A list of class c("CosinorM", "lm") containing:
parm: Parameters specified in the model
tau: The assumed period length
time: The time coordinates of the recording
method: The estimation method used
coef.cosinor: Named numeric vector with entries:
MESOR: Mid-line estimating statistic of rhythm
Amplitude: Predicted peak activity magnitude
Acrophase: Acrophase in radian (time-of-peak)
Beta: the coefficient of the cosine function
Gamma: the coefficient of the sine function
post.hoc: Post-hoc peak/trough diagnostics derived from fitted.values at observation angles (MESOR.ph, Bathyphase.ph.time, Trough.ph, Acrophase.ph.time, Peak.ph, Amplitude.ph)
extra: only available for ultradian (i.e., less than
24hour) single-component model
vcov: Robust variance-covariance matrix
se: Standard errors
Inherits all components from lm.
Cornelissen G. Cosinor-based rhythmometry. Theoretical Biology and Medical Modelling. 2014-12-01 2014;11(1):16. doi:10.1186/1742-4682-11-16
Chambers, J. M. (1992) Linear models. Chapter 4 of Statistical Models in S eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.
Wilkinson, G. N. and Rogers, C. E. (1973). Symbolic descriptions of factorial models for analysis of variance. Applied Statistics, 22, 392-399. doi:10.2307/2346786.
Harvey, A. C. (1976). Estimating Regression Models with Multiplicative Heteroscedasticity. Econometrica, 44(3), 461-465. doi:10.2307/1913974
require (stats) require (graphics) ## Not run: # Import data data( FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-27") fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = 24, method = "OLS" ) # inspect coefficients fit$coef.cosinor # plot Cosinor in hours plot(fit$time, fit$fitted.values, type = "l", xlab = "Hour", ylab = "24-Hour Cosinor Model") ## End(Not run)require (stats) require (graphics) ## Not run: # Import data data( FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-27") fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = 24, method = "OLS" ) # inspect coefficients fit$coef.cosinor # plot Cosinor in hours plot(fit$time, fit$fitted.values, type = "l", xlab = "Hour", ylab = "24-Hour Cosinor Model") ## End(Not run)
Fit an intensity‑weighted Gaussian kernel density estimate (KDE) on circular time (hours of day) weighted by activity and extract first-harmonic cosinor summaries.
CosinorM.KDE(time, activity, bw = 0.8, arctan2 = TRUE, dilute = FALSE)CosinorM.KDE(time, activity, bw = 0.8, arctan2 = TRUE, dilute = FALSE)
time |
Numeric vector of time coordinates for each data point. Values
are interpreted modulo 24 and must lie in |
activity |
Numeric vector of activity counts from an actigraphy device in correspondance to each time point. Non-numeric inputs will be coerced. All-zero or non-finite activity values produce an error. |
bw |
Numeric scalar. Kernel standard deviation (SD) controlling s
moothing. bw is interpreted in the same units as the angular scale after
conversion: the implementation converts 'bw' from hours to radians
internally using |
arctan2 |
Logical; if TRUE (default) acrophase is computed with
|
dilute |
Logical; if FALSE (default), all essential parameters would be produced. When set to TRUE, only cosinor coefficients are returned. This is suited for post-hoc processes, such as computing confidence interval via nonparametric bootstrap |
This function builds a kernel-smoothed circular activity intensity
from event time (hours in ) and activity. The intensity
is estimated on a regular angular grid over using a
wrapped Gaussian kernel with specified bandwidth and normalized to
form a circular density over phase. Cosinor summaries (MESOR, Beta,
Gamma, Amplitude, Acrophase) are obtained by numerical integration of
the fitted density using trapezoid-rule quadrature.
Cosinor parameters are obtained by numerical integration of the KDE on the grid:
MESOR: mean level of the fitted curve, .
: cosine coefficient, .
: sine coefficient, .
Amplitude: magnitude of the first harmonic, .
Acrophase: peak time, , expressed
in radians and converted to hours.
The grid integrals are computed with trapezoid weights :
where is the normalized KDE at grid angle ,
is the kernel denominator at that grid point, and
rescales the fitted density back to the activity scale.
Notes:
Normalization factors and follow from the
orthogonality of sine and cosine on .
The KDE summarizes the first harmonic of the rest–activity pattern over one cycle; higher harmonics are not extracted.
The trapezoid rule ensures numerical stability by integrating over a dense, evenly spaced grid.
The dense grid excludes the duplicate endpoint (grid in
) to avoid duplicated quadrature nodes.
Grid and observation trapezoid weights correct for irregular sampling and yield stable approximations to continuous integrals.
Grid points with near-zero denominator are set to NA and excluded from integrals to avoid
division-by-zero artifacts.
Residaul Variance and Effective Degree of Freedom
Regression (projection hat matrix):
where is the number of parameters (degrees of freedom used by the
fit).
Linear kernel smoothing:
Fitted values are given by the linear smoother
where is the hat matrix induced by the kernel weights (not a
projection).
When defining residuals as and ,
the unbiased estimator under the Gaussian kernel smoother can be written as
where,
is the effective degrees of freedom used by the smoother (analogous to the number of parameters).
is a correction
term because
is not an orthogonal projection.
A list of class c("CosinorM.KDE") with elements:
parm: Parameters specified in the model (list with time,
activity, bw)
tau: Period in hours (default to 24hour)
kdf: A data.frame with the following columns:
theta: Angular positions (radians) at the observation angles
density: Estimated PDF values at the observation angles
(integrates to 1 over when scaled)
trapizoid.weight: Numeric vector of trapezoid integration weights at observation angles
kernel.weight: Denominator from kernel convolution (kernel mass at each observation angle)
fitted.values: Normalized fitted KDE (activity-scale) at observation angles
fitted.var: Variance estimate of the fitted values (for SE)
fitted.se: Standard error of the fitted values
hour: Corresponding clock time in hours
coef.cosinor: Named numeric vector with entries:
MESOR: the mean of activity density over 24 hours
Amplitude: the first-harmonic amplitude derived from Beta and Gamma
Acrophase: Acrophase in radians (time-of-peak) of the dominant daily component
Acrophase.hr: Acrophase converted to clock hours in [0,24)
Beta: coefficient equivalent to the cosine-weighted integral of the KDE
Gamma: coefficient equivalent to the sine-weighted integral of the KDE
post.hoc: Post-hoc peak/trough diagnostics derived from fitted.values at observation angles (MESOR.ph, Bathyphase.ph.time, Trough.ph, Acrophase.ph.time, Peak.ph, Amplitude.ph)
The function errors if all(activity) == 0 or if
activity contains
non-finite values.
Very small bw can cause near-zero denominator values
(numerical instability) and produce NA or an error; very large
bw approaches a near-uniform kernel and will wash out temporal
structure.
Cornelissen G. Cosinor-based rhythmometry. Theoretical Biology and Medical Modelling. 2014-12-01 2014;11(1):16. doi:10.1186/1742-4682-11-16
On Nonparametric Density Estimation for Circular Data: An Overview , bookTitle= Directional Statistics for Innovative Applications: A Bicentennial Tribute to Florence Nightingale. Springer Nature Singapore; 2022:351–378.
Cremers J, Klugkist I. One Direction? A Tutorial for Circular Data Analysis Using R With Examples in Cognitive Psychology. Methods. Front Psychol. 2018-October-30 2018;9(2040):2040. doi:10.3389/fpsyg.2018.02040
## Not run: # Import data FlyEast BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset ( x = df, subset = df$Date == "2017-10-27" ) fit <- CosinorM.KDE ( time = df$Time, activity = df$Activity ) # inspect coefficients fit$coef.cosinor # plot KDE in hours plot ( x = fit$kdf$hour, y = fit$kdf$density, type = "l", xlab = "Hour", ylab = "KDE" ) ## End(Not run)## Not run: # Import data FlyEast BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset ( x = df, subset = df$Date == "2017-10-27" ) fit <- CosinorM.KDE ( time = df$Time, activity = df$Activity ) # inspect coefficients fit$coef.cosinor # plot KDE in hours plot ( x = fit$kdf$hour, y = fit$kdf$density, type = "l", xlab = "Hour", ylab = "KDE" ) ## End(Not run)
For an ordered vector of Dates or date-times, 'Date2TotalT()' calculates the interval from each element to the next (and for the last element, to the following calendar day at midnight) and returns these durations in the requested time unit.
Date2TotalT(DT, TUnit = "hour", TZ = "local")Date2TotalT(DT, TUnit = "hour", TZ = "local")
DT |
A vector of class |
TUnit |
Character string specifying the unit for the output durations. Must be one of "hour", "minute", or "second". Comparison is case-insensitive. Default is "hour", meaning the returned values are in decimal hours. |
TZ |
The time zone when the recording started. (default = "local", which means user's local time zone) |
A numeric vector of the same length as DT. Each element is the
elapsed time between the corresponding entry in DT and the next
boundary (either the next date-time in Date, or midnight following
the last date), expressed in the units given by TUnit.
# Two calendar days: returns c(24, 24) hours Date2TotalT (as.Date (c ("2021-01-01", "2021-01-02")), "hour") # Working in minutes Date2TotalT (as.POSIXct (c ( "2021-06-10 08:00:00", "2021-06-10 14:30:00" )), "minute") # In seconds (case-insensitive unit name) Date2TotalT (as.Date ("2022-12-31"), "SeCoNd")# Two calendar days: returns c(24, 24) hours Date2TotalT (as.Date (c ("2021-01-01", "2021-01-02")), "hour") # Working in minutes Date2TotalT (as.POSIXct (c ( "2021-06-10 08:00:00", "2021-06-10 14:30:00" )), "minute") # In seconds (case-insensitive unit name) Date2TotalT (as.Date ("2022-12-31"), "SeCoNd")
This function will automatically detect possible date format. Users can choose to either reformat the date or report the datetime format detected.
Identifies the likely date format used in character strings and optionally converts these strings to Date objects. This utility is intended to support pre-processing of timestamp data with varied or unknown formatting. When ambiguity arises (e.g., day-month versus month-day ordering), the function defaults to the first compatible format unless explicitly guided by a delimiter or by manual correction.
DateFormat(DT, as.date = TRUE, Delim = NULL)DateFormat(DT, as.date = TRUE, Delim = NULL)
DT |
A character vector containing date or date-time strings. |
as.date |
Logical. If TRUE (default), returns converted Date objects.
If FALSE, returns the detected format string (e.g., |
Delim |
Optional. A single character (e.g., |
If as.date = TRUE, returns a vector of class Date.
If as.date = FALSE, returns a character string representing the
detected format. When multiple formats coexist or no valid format is
detected, warnings are issued and default behavior is applied.
If no format matches, returns NA and issues a warning.
# Consistent format across all strings DT <- c ("2017/05/02", "2000/02/28", "1970/01/02") DateFormat (DT, as.date = FALSE) # returns parsed Date vector ## Not run: # Mixed formats within a vector DT <- c ( "2017/05/02", "2000.Feb.28", "1970-11-02", "January 01, 2025", "December 12, 1980" ) lapply (DT, DateFormat) # element-wise parsing ### We expect that many of these format will not work because they contain ### text DT <- c ( "2017/05/02", "2000.02.28", "1970-11-02", "01, 01, 2025", "12, 12, 1980" ) # Recommended usage for mixed formats: lapply (DT, DateFormat, Delim = ",") # element-wise parsing for (x in DT) { print (DateFormat (x, Delim = ",")) } # displays format/warning per entry # Avoid using sapply, because it will convert them into numeric form sapply (DT, DateFormat) ## End(Not run)# Consistent format across all strings DT <- c ("2017/05/02", "2000/02/28", "1970/01/02") DateFormat (DT, as.date = FALSE) # returns parsed Date vector ## Not run: # Mixed formats within a vector DT <- c ( "2017/05/02", "2000.Feb.28", "1970-11-02", "January 01, 2025", "December 12, 1980" ) lapply (DT, DateFormat) # element-wise parsing ### We expect that many of these format will not work because they contain ### text DT <- c ( "2017/05/02", "2000.02.28", "1970-11-02", "01, 01, 2025", "12, 12, 1980" ) # Recommended usage for mixed formats: lapply (DT, DateFormat, Delim = ",") # element-wise parsing for (x in DT) { print (DateFormat (x, Delim = ",")) } # displays format/warning per entry # Avoid using sapply, because it will convert them into numeric form sapply (DT, DateFormat) ## End(Not run)
Determine if Dates Fall in Daylight Saving Time for the Given Time Zone(s)
DST(DT, TZ = "local")DST(DT, TZ = "local")
DT |
A vector of class 'Date', 'POSIXct', or 'POSIXlt', representing the dates/times to test. These need not be sorted. |
TZ |
A single string naming an IANA time zone (e.g. 'America/New_York').
If '"local"', it will extract local time zone using |
For each element of 'DT', returns 'TRUE' if that date-time is in daylight saving time (DST) under the specified time zone. The function handles transitions by detecting the "gain" or "loss" of hours via 'DST2GL()' and flipping the DST flag on the transition day.
A logical vector of the same length as 'DT'.
'TRUE' indicates the timestamp falls in DST
'FALSE' indicates standard time.
# Standard use: New York in summer vs. winter dates <- as.POSIXct (c ("2021-06-15", "2021-12-15"), tz = "America/New_York") DST (dates, TZ = "America/New_York") # Around the spring-forward transition trans <- as.Date (c ("2021-03-13", "2021-03-14", "2021-03-15")) DST (trans, TZ = "America/New_York") # Using the local system time zone DST (as.POSIXct ("2023-07-01 12:00:00"), TZ = "local")# Standard use: New York in summer vs. winter dates <- as.POSIXct (c ("2021-06-15", "2021-12-15"), tz = "America/New_York") DST (dates, TZ = "America/New_York") # Around the spring-forward transition trans <- as.Date (c ("2021-03-13", "2021-03-14", "2021-03-15")) DST (trans, TZ = "America/New_York") # Using the local system time zone DST (as.POSIXct ("2023-07-01 12:00:00"), TZ = "local")
DST2GL computes, for each date-time entry, how many hours a day
deviates from the standard 24hours because of DST shifts.
Internally it calls Date2TotalT() in seconds, subtracts
the 86400s of a normal day, and converts the remainder to hours.
DST2GL(DT, TZ = "local")DST2GL(DT, TZ = "local")
DT |
A vector of class |
TZ |
The time zone when the recording started. (default = "local", which means user's local time zone) |
A numeric vector of the same length as DT. Each
value is the number of hours that day is longer
(positive) or shorter (negative) than 24h. A zero means no DST
shift on that date.
# Example around a typical spring-forward transition (e.g. US second Sunday # in March) dates <- as.Date ("2021-03-14") # On 2021-03-14 clocks jumped forward: day is 23h so output = -1 DST2GL (dates) # Example around a fall-back transition (e.g. first Sunday in November) dates <- as.Date ("2021-11-07") # On 2021-11-07 clocks fall back: day is 25h so output = +1 DST2GL (dates) # Multiple Dates sapply (c ("2021-03-13", "2021-03-14", "2021-03-15"), DST2GL)# Example around a typical spring-forward transition (e.g. US second Sunday # in March) dates <- as.Date ("2021-03-14") # On 2021-03-14 clocks jumped forward: day is 23h so output = -1 DST2GL (dates) # Example around a fall-back transition (e.g. first Sunday in November) dates <- as.Date ("2021-11-07") # On 2021-11-07 clocks fall back: day is 25h so output = +1 DST2GL (dates) # Multiple Dates sapply (c ("2021-03-13", "2021-03-14", "2021-03-15"), DST2GL)
This sample data is a modified version of a continuous wrist-worn actigraphy recording (Philips 'ActiWatch5') collected over a month. The data was originally collected to monitor the influence of jetleg on professional athelets' performance during competitions.
data(FlyEast)data(FlyEast)
A modified data with 40 thousands plus rows and 3 variables:
The activity count measured by a tri-axis actigraphy
The light exposure data from the light sensor. All values are zero since the function was not disabled during the recording.
A binary indicator generated when the wearer press the button to record onset of sleep or awake.
BriefSum TAdjust TravelLog
IANA
This is the subset of the travel-adjusted 'FlyEast' data. The data was originally collected to monitor the influence of jetleg on professional athelets' performance during competitions.
data(FlyEast_adj)data(FlyEast_adj)
An adjusted FlyEast data with 40 thousands plus rows and 6 variables:
The time coordinates of each recorded activies in the standard date and time joint format
The date of each recorded activies
The simplified time coordinates in hour form converted from 'DateTime'
The activity count measured by a tri-axis actigraphy
Numeric values denoted the sequence of each activity count in the recording
Summary annotation derived from BriefSum.
Creates a time-series 'scatterplot' of activity counts from an 'ActiGlobe' data.frame,marking each midnight boundary with a vertical dashed line and 'coloring' points that were flagged (e.g. travel overlaps or unallocated epochs).
ggActiGlobe(df, Bdf, VAct = NULL, VDT = "DateTime")ggActiGlobe(df, Bdf, VAct = NULL, VDT = "DateTime")
df |
A data.frame of annotated actigraphy epochs. Must include:
- An activity column named by |
Bdf |
A |
VAct |
Optional character. Name of the activity column in |
VDT |
Optional character. Name of the |
A ggplot object showing:
- Activity counts vs. time.
- Dashed vertical lines at each midnight.
- Points 'colored' by whether they were flagged in 'Note'.
## Not run: library(ActiGlobe) # Overview the Uncorrected Longitudinal Recording data(FlyEast) BdfList <- BriefSum( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) p <- ggActiGlobe( df = BdfList$df, Bdf = BdfList$Bdf, VAct = "Activity", VDT = "DateTime" ) print(p) # Overview the Corrected Longitudinal Recording data(TLog) BdfList$Bdf.adj <- TAdjust(BdfList$Bdf, TLog) p2 <- ggActiGlobe( df = BdfList$df, Bdf = BdfList$Bdf, VAct = "Activity", VDT = "DateTime" ) print(p2) # Pro-tip: [`cowplot`] can help stack the time series graphs in one # single plot ## End(Not run)## Not run: library(ActiGlobe) # Overview the Uncorrected Longitudinal Recording data(FlyEast) BdfList <- BriefSum( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) p <- ggActiGlobe( df = BdfList$df, Bdf = BdfList$Bdf, VAct = "Activity", VDT = "DateTime" ) print(p) # Overview the Corrected Longitudinal Recording data(TLog) BdfList$Bdf.adj <- TAdjust(BdfList$Bdf, TLog) p2 <- ggActiGlobe( df = BdfList$df, Bdf = BdfList$Bdf, VAct = "Activity", VDT = "DateTime" ) print(p2) # Pro-tip: [`cowplot`] can help stack the time series graphs in one # single plot ## End(Not run)
Create visualization of a CosinorM or CosinorM.KDE fit using ggplot2. The plot shows the parametric cosinor fit over a fine time grid, optional pointwise confidence bands, observed data points, MESOR line, acrophase verticals, amplitude annotation segments, and labelled parameter values when requested.
ggCosinorM( object, labels = TRUE, ci = TRUE, ci_level = 0.95, n = 400, point_size = 0.5, title_extra = NULL, legend.position = "right", ... )ggCosinorM( object, labels = TRUE, ci = TRUE, ci_level = 0.95, n = 400, point_size = 0.5, title_extra = NULL, legend.position = "right", ... )
object |
A fitted model of class |
labels |
Logical; Default: TRUE, which places repelled labels on the plot with MESOR, amplitude(s), and acrophase(s). |
ci |
Logical; Default: TRUE, which computes and draws pointwise parametric confidence bands for the fitted cosinor curve using the model covariance. |
ci_level |
Numeric scaler. The range of the confidence interval, expressed in numeric value between 0 and 1. Default: 0.95 |
n |
Integer scaler. Number of points on the fine prediction grid used to draw the fitted cosinor and confidence ribbon. Default: 400 |
point_size |
Numeric scaler. Plotting size for observed points. Default: 0.5 |
title_extra |
Optional character string appended to the plot title for extra context. |
legend.position |
Position of the legend on the plot; default is "right". Other options include "top", "bottom", "left", or a numeric vector of length two specifying x and y coordinates. |
... |
Additional arguments (currently ignored) kept for future update. |
A 'ggplot' object representing the cosinor model fit visualization.
ggplot,
geom_label_repel,
predict
## Not run: # Import data data (FlyEast) BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-28") fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = 24, method = "OLS" ) p <- ggCosinorM ( object = fit, labels = TRUE, ci = TRUE, ci_level = 0.95, title_extra = "2017-10-24" ) print (p) ## End(Not run)## Not run: # Import data data (FlyEast) BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract actigraphy data from a single day df <- BdfList$df df <- subset (df, df$Date == "2017-10-28") fit <- CosinorM ( time = df$Time, activity = df$Activity, tau = 24, method = "OLS" ) p <- ggCosinorM ( object = fit, labels = TRUE, ci = TRUE, ci_level = 0.95, title_extra = "2017-10-24" ) print (p) ## End(Not run)
A dictionary for standard abbreviation and labels of time-zone and their corresponding UTC offset.
data(IANA)data(IANA)
A modified IANA 2025b database
Full name of the country (e.g., "Canada").
Two-letter ISO 3166-1 alpha-2 country code (e.g., "CA").
Canonical IANA timezone identifier (e.g., "America/Montreal").
Alternative or historical identifiers linked to the IANA timezone.
Short code or identifier representing the timezone, often aligned with ISO or custom dataset conventions (e.g., "EST", "PST").
Numeric UTC offset in hours, representing the difference from Coordinated Universal Time (e.g., -5, +9).
Logical flag indicating whether the timezone observes daylight saving time (TRUE/FALSE).
Current daylight saving time status at the time of data capture (e.g., "DST Active").
Abbreviation in effect at the reference date/time, which may be a daylight saving abbreviation (e.g., "EDT") or a standard abbreviation (e.g., "EST").
Human-readable name of the timezone currently in effect, reflecting whether daylight saving time is active (e.g., "Eastern Daylight Time" in summer, "Eastern Standard Time" in winter).
UTC offset in hours at the reference date/time, including any daylight saving adjustment if applicable (e.g., -4 during EDT, -5 during EST).
Abbreviation used during standard (non-daylight saving) time only (e.g., "EST").
Human-readable name of the timezone during standard time, without daylight saving adjustment (e.g., "Eastern Standard Time").
UTC offset in hours during standard time, excluding daylight saving adjustment (e.g., -5).
Convert numeric values representing UTC offsets (in hours, with optional fractional parts for minutes) into standardized character strings of the form '"UTC+HH:MM"' or '"UTC-HH:MM"'. This is useful for translating numeric time zone offsets into human-readable UTC offset notation.
Num2UTC(x)Num2UTC(x)
x |
UTC Offsets <e.g., "UTC+09:30" or "UTC-07:00"> |
A character vector of standard UTC offsets
# Convert UTC to numeric values x <- c (9.5, -7) x1 <- Num2UTC (x) print (x1)# Convert UTC to numeric values x <- c (9.5, -7) x1 <- Num2UTC (x) print (x1)
Convert 'acrophase' in radian to clock time based on tau.
Rad2Hr(x, tau)Rad2Hr(x, tau)
x |
Numeric vector of phases in radian. |
tau |
Numeric scalar. Period length in the same time units you want returned (for hours use 24). Must be a single numeric value > 0 and <= 24. |
Numeric vector of times in . NA values propagate.
Rad2Hr (pi / 2, tau = 24) Rad2Hr (c (-pi / 2, 0, pi, 3 * pi / 2), tau = 24)Rad2Hr (pi / 2, tau = 24) Rad2Hr (c (-pi / 2, 0, pi, 3 * pi / 2), tau = 24)
'TAdjust()' is a function that corrects data points and time-shift based on travelling log. Note that it is important to ensure that the UTC-offset value is correct. When in doubt, please use the UTC function or consult IANA table in the package. Daylight saving will not be reassessed as in BriefSum function.
TAdjust(Bdf, TLog, TZ = NULL, fork = FALSE)TAdjust(Bdf, TLog, TZ = NULL, fork = FALSE)
Bdf |
A |
TLog |
A structured travel log containing date of travel and local time zone. Use 'TravelLog()' to generate template. |
TZ |
The time zone when the recording started. (default = "NULL", which will disregard the use of the initial geographical location-based time zone indicator) |
fork |
Logical, if TRUE, it will use parallel processing to speed up the computation. Default is FALSE. |
A BriefSum object with adjusted data points and time
shift based on travel log.
## Not run: # Import sample data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-19 13:45:00", TZ = 'America/New_York' ) # Extract only the summary report Bdf <- BdfList$Bdf # Import sample travel Log data (TLog) # Adjust time shift based on travel log Bdf.adj <- TAdjust (Bdf = Bdf, TLog = TLog, TZ = 'America/New_York') # Display the summary View (Bdf) View (Bdf.adj) ### Focus on the dates after 2017-11-01 ## End(Not run)## Not run: # Import sample data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-19 13:45:00", TZ = 'America/New_York' ) # Extract only the summary report Bdf <- BdfList$Bdf # Import sample travel Log data (TLog) # Adjust time shift based on travel log Bdf.adj <- TAdjust (Bdf = Bdf, TLog = TLog, TZ = 'America/New_York') # Display the summary View (Bdf) View (Bdf.adj) ### Focus on the dates after 2017-11-01 ## End(Not run)
This function will automatically detect possible time format. Users can choose to either reformat the date or report the datetime format detected.
TimeFormat(time, as.time = FALSE)TimeFormat(time, as.time = FALSE)
time |
A character string of time. |
as.time |
A binary operator indicating whether to return a converted time based on the detection or the time format. (default: FALSE, which returns time format) |
If as.time = TRUE, returns a character vector of the input times
reformatted according to the detected format. Each element corresponds to
the respective entry in time.
If as.time = FALSE, returns a character scalar giving the
best-matching time format string.
If no format matches, returns NA and issues a warning.
# Example 1: When all dates have the same format ## Create and store a date in a variable called Time Time <- c ( "2017/05/02 23:00:01", "1970/01/02 05:10:33", "2000/02/28 07:00:00" ) ## Ask TimeFormat to tell us the format of the time. TimeFormat (time = Time, as.time = FALSE) # Example 2: When multiple formats co-exist in a variable ## Create and store dates and time in a variable called Time Time <- c ( "2017/05/02 23:00:01", "2000/02/28 07:00", "1970/01/02", "2022/11/28 08:35 PM" ) ## Ask TimeFormat to tell us the format of the Time. ### DO This! #### Option 1. print (lapply (Time, TimeFormat)) #### Option 2. To match the warning message to the items for (x in Time) { print (TimeFormat (x)) } ### DO NOT! ### print(TimeFormat(time = Time)) ### Note, this process will fail because there are multiple formats# Example 1: When all dates have the same format ## Create and store a date in a variable called Time Time <- c ( "2017/05/02 23:00:01", "1970/01/02 05:10:33", "2000/02/28 07:00:00" ) ## Ask TimeFormat to tell us the format of the time. TimeFormat (time = Time, as.time = FALSE) # Example 2: When multiple formats co-exist in a variable ## Create and store dates and time in a variable called Time Time <- c ( "2017/05/02 23:00:01", "2000/02/28 07:00", "1970/01/02", "2022/11/28 08:35 PM" ) ## Ask TimeFormat to tell us the format of the Time. ### DO This! #### Option 1. print (lapply (Time, TimeFormat)) #### Option 2. To match the warning message to the items for (x in Time) { print (TimeFormat (x)) } ### DO NOT! ### print(TimeFormat(time = Time)) ### Note, this process will fail because there are multiple formats
A modified travel log documenting the dates when the wearer departs for long-distance travel.
data(TLog)data(TLog)
A data frame with over 40,000 rows and 5 variables:
Pseudonym of the wearer.
UTC offset of the wearer's location or destination.
Binary indicator (TRUE/FALSE) for whether daylight saving time is observed at the location or destination.
Start date of the wearer's initial location or date of departure.
Optional date when the wearer departs again from the initial location or previous destination.
Generate the Travel Log Template Needed for Time Zone Correction
TravelLog(Write = FALSE, Dir = NULL)TravelLog(Write = FALSE, Dir = NULL)
Write |
A binary code to indicate whether to write a .csv file containing the template needed for the travel log. (default = FLASE) When set to FALSE, the template will be returned as an object. When set to TRUE, user must provide the target directory where they wish to store the template. |
Dir |
The directory where the travel log template to be exported <e.g. "C:/Users/___YOUR USERNAME___/UPSTREAM FOLDER/.../FOLDER NAME/"> |
a travel-log template as a data.frame or written as a CSV file
Tlg <- TravelLog (Write = FALSE) print (Tlg)Tlg <- TravelLog (Write = FALSE) print (Tlg)
Compute UTC offset based on Time Zone and Date
TZ2UTC(DT, TZ = "local")TZ2UTC(DT, TZ = "local")
DT |
The date in the format as "2021-03-05" |
TZ |
The time zone when the recording started. Default = "local", which means user's local time zone |
A character string indicating the UTC offset, e.g., "UTC-05:00"
x <- as.Date (c ("2017-10-24", "2017-11-20")) TZ2UTC (DT = x, TZ = "America/New_York") ## Expect two different UTCs ## Not run: # A vector of dates x <- seq.Date ( from = as.Date ("2017-10-24"), to = as.Date ("2017-11-27"), by = "day" ) # If the user resides in a country that follows daylight saving time TZ2UTC (DT = x, TZ = "local") # If not # TZ2UTC(DT = x, TZ = "America/New_York") ## End(Not run)x <- as.Date (c ("2017-10-24", "2017-11-20")) TZ2UTC (DT = x, TZ = "America/New_York") ## Expect two different UTCs ## Not run: # A vector of dates x <- seq.Date ( from = as.Date ("2017-10-24"), to = as.Date ("2017-11-27"), by = "day" ) # If the user resides in a country that follows daylight saving time TZ2UTC (DT = x, TZ = "local") # If not # TZ2UTC(DT = x, TZ = "America/New_York") ## End(Not run)
Convert Standard UTC Offset to Numbers
UTC2Num(x)UTC2Num(x)
x |
Character string of UTC offsets, e.g., "UTC+09:30" or "UTC-07:00". |
Numeric values of UTC offsets
# Convert UTC to numeric values x <- c ("UTC+09:30", "UTC-07:00") x1 <- UTC2Num (x) print (x)# Convert UTC to numeric values x <- c ("UTC+09:30", "UTC-07:00") x1 <- UTC2Num (x) print (x)
Tests whether any IANA time zone associated with a given UTC offset undergoes daylight saving time (DST) transitions. The function identifies all zones matching the specified UTC offset and evaluates whether a time change occurs between winter and summer timestamps.
UTCwDST(UTCs, DT = NULL, fork = FALSE)UTCwDST(UTCs, DT = NULL, fork = FALSE)
UTCs |
A character vector or numeric vector representing UTC offsets.
Accepted formats include "UTC+08:00", "UTC-05:00", or numeric values
like "+8", "-5", etc. The function internally maps UTC strings to numeric
offsets using |
DT |
A POSIXct date/time used as the reference point for offset comparison. Defaults to January 1, 2021 UTC if 'NULL'. |
fork |
Logical, if TRUE, it will use parallel processing to speed up the computation. Default is FALSE. |
For each value in UTCs, the function retrieves the corresponding IANA
time zones whose offset matches the specified UTC string or numeric hour.
It then compares the DST status of each zone on January 1 and July 15.
If at least one zone shows a shift in DST status between the two dates,
the function returns 'TRUE' for that offset.
A logical vector the same length as UTCs. Each entry is 'TRUE' if at
least one time zone at the specified offset undergoes a DST transition,
'FALSE' otherwise.
## Not run: # Check for DST transitions in UTC+1 and UTC+8 UTCwDST (UTCs = c ("UTC+01:00", "UTC+08:00")) # Use numeric offset directly UTCwDST (UTCs = c (1, 8)) # UTC-5 commonly includes DST zones (e.g., New York) UTCwDST (UTCs = -5) ## End(Not run)## Not run: # Check for DST transitions in UTC+1 and UTC+8 UTCwDST (UTCs = c ("UTC+01:00", "UTC+08:00")) # Use numeric offset directly UTCwDST (UTCs = c (1, 8)) # UTC-5 commonly includes DST zones (e.g., New York) UTCwDST (UTCs = -5) ## End(Not run)
A function that exports two types of files locally. 1. A summary of the entire recording (.csv). 2. Daily activity recordings in individual files (.txt). The default deliminator is set to be space, with '.' as the decimal indicator. As such, it should be noted that some transformation may be needed when opening in EXCEL on a computer with non-English EU settings.
write.act( Dir, ID, df, Bdf, TUnit = "hour", VAct = NULL, VTm = NULL, Incomplete = FALSE, Travel = TRUE, Simple = FALSE )write.act( Dir, ID, df, Bdf, TUnit = "hour", VAct = NULL, VTm = NULL, Incomplete = FALSE, Travel = TRUE, Simple = FALSE )
Dir |
The directory where the recordings to be exported <e.g. "C:/Users/___YOUR USERNAME___/UPSTREAM FOLDER/.../FOLDER NAME/"> |
ID |
The subject's ID which would be used to create a folder. |
df |
A data.frame of raw actigraphy recording. Both time and activity count should be included in the 'df'. See 'VAct' and 'VTm' for further detail. |
Bdf |
A |
TUnit |
Character; time–unit for the x–axis of each day's timeline. Must be one of 'day', 'hour', 'minute' or 'second'. Default is 'hour'. |
VAct |
Optional character. Name of the activity column in 'df'. If NULL, defaults to the second column of 'df'. |
VTm |
Optional character. Name of the time index column in 'df'. If NULL, defaults to the first column of 'df'. |
Incomplete |
Logical; if TRUE, days flagged 'Incomplete Recording' (i.e. <24 h) are retained in the data list with recordings segmented by day. Default = FALSE (these days are removed). |
Travel |
Logical; if TRUE, days flagged 'Travel' are retained although some data points from an earlier adjacent calendar day may be duplicated (a warning is issued). If FALSE, travel days and the day before/after are excluded. Default = TRUE. |
Simple |
Logical; if TRUE, only columns stored in the original recordings will be exported. If FALSE, all information stored in 'df' will be generated. Default = FALSE |
Text files ".txt" containing segmented recordings of each day and 'Bdf' from
BriefSum
Text File: Recordings segmented by the recording date
Summary: Bdf exported as ".csv" file.
## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract the quick summary of the recording Bdf <- BdfList$Bdf ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] df <- BdfList$df # Export daily recordings and the summary report write.act ( Dir = getwd (), ## Export to the current working directory ID = "JD", df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time" ) ## To see what was exported copy the path generated by the code below and ## paste it as an url in a web browser or the file explorer. getwd () ## End(Not run)## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract the quick summary of the recording Bdf <- BdfList$Bdf ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] df <- BdfList$df # Export daily recordings and the summary report write.act ( Dir = getwd (), ## Export to the current working directory ID = "JD", df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time" ) ## To see what was exported copy the path generated by the code below and ## paste it as an url in a web browser or the file explorer. getwd () ## End(Not run)
A multi-wrapper function which generate data trend using
geom_smooth and model plot using
CosinorM or CosinorM.KDE. All daily results
could be found in the exported report. A summary file in .csv format is
also generated to update the original 'Bdf' with cosinor model coefficients
for each day.
write.cosinor( Dir, ID, DailyAct, Bdf, VAct = NULL, VTm = NULL, method = "OLS", tau = 24, ph = FALSE, overwrite = FALSE )write.cosinor( Dir, ID, DailyAct, Bdf, VAct = NULL, VTm = NULL, method = "OLS", tau = 24, ph = FALSE, overwrite = FALSE )
Dir |
The directory where the recordings to be exported <e.g. "C:/Users/___YOUR USERNAME___/UPSTREAM FOLDER/.../FOLDER NAME/"> |
ID |
The subject's ID which would be used to create a folder. |
DailyAct |
A data.frame list generated by 'Act2Daily()' |
Bdf |
A |
VAct |
Optional character. Name of the activity column in each data.frame object ('df') in 'DailyAct'. If NULL, defaults to the second column of 'df'. |
VTm |
Optional character. Name of the activity column in each data.frame object ('df') in 'DailyAct'. If NULL, defaults to the first column of 'df'. |
method |
Character string specifying estimation method
|
tau |
Numeric scalar or vector for the assumed circadian period,
passed to |
ph |
Optional logical scaler; if only a single period is assigned to tau, TRUE will force the function to append the post-hoc circadian estimates instead of the model estimates. (default: FALSE) |
overwrite |
Logical; if TRUE, existing files with the same name will be overwritten. Default = FALSE. |
Creates a multi-page '.pdf' visual document and a text-based '.csv' summary.
PDF A multi-page PDF written to 'pdfDir' (one file per 'ID'). Each page corresponds to a recording day and contains two panels: the top panel shows the raw activity (points) and a smoothed trend; the bottom panel shows the model fit for the same day
'Summary.csv' An updated 'Bdf' documentation with one row per recording day. Model-based circadian parameters are appened at the end of the file for each day.
Act2Daily CosinorM CosinorM.KDE
## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract the quick summary of the recording Bdf <- BdfList$Bdf df <- BdfList$df ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] ## Segment Data by Day dfList <- Act2Daily ( df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time", Incomplete = TRUE, Travel = TRUE ) ## Generate graphic summary of daily recordings in pdf with an addition ## `Summary` file just like write.act write.cosinor ( Dir = getwd (), ## Export to the current working directory ID = "JD", DailyAct = dfList$Daily_df, Bdf = Bdf, VAct = "Activity", VTm = "Time" ) ## To see what was exported copy the path generated by the code below and ## paste it as an url in a web browser or the file explorer. getwd () ## End(Not run)## Not run: # Import data data (FlyEast) # Create quick summary of the recording with adjustment for daylight saving. BdfList <- BriefSum ( df = FlyEast, SR = 1 / 60, Start = "2017-10-24 13:45:00" ) # Let's extract the quick summary of the recording Bdf <- BdfList$Bdf df <- BdfList$df ### Note that since the original data was affected by travel-induced time ### shift, the recordings would not be properly segmented from 2017-11-02. ## To avoid time shift due to travelling, we will keep only the first 8 days. Bdf <- Bdf [1:8, ] ## Segment Data by Day dfList <- Act2Daily ( df = df, Bdf = Bdf, VAct = "Activity", VTm = "Time", Incomplete = TRUE, Travel = TRUE ) ## Generate graphic summary of daily recordings in pdf with an addition ## `Summary` file just like write.act write.cosinor ( Dir = getwd (), ## Export to the current working directory ID = "JD", DailyAct = dfList$Daily_df, Bdf = Bdf, VAct = "Activity", VTm = "Time" ) ## To see what was exported copy the path generated by the code below and ## paste it as an url in a web browser or the file explorer. getwd () ## End(Not run)