Type: Package
Title: Raw Accelerometer Data Analysis
Version: 3.2-6
Date: 2025-04-25
Maintainer: Vincent T van Hees <v.vanhees@accelting.com>
Description: A tool to process and analyse data collected with wearable raw acceleration sensors as described in Migueles and colleagues (JMPB 2019), and van Hees and colleagues (JApplPhysiol 2014; PLoSONE 2015). The package has been developed and tested for binary data from 'GENEActiv' https://activinsights.com/, binary (.gt3x) and .csv-export data from 'Actigraph' https://theactigraph.com devices, and binary (.cwa) and .csv-export data from 'Axivity' https://axivity.com. These devices are currently widely used in research on human daily physical activity. Further, the package can handle accelerometer data file from any other sensor brand providing that the data is stored in csv format. Also the package allows for external function embedding.
URL: https://github.com/wadpac/GGIR/, https://groups.google.com/forum/#!forum/RpackageGGIR, https://wadpac.github.io/GGIR/
BugReports: https://github.com/wadpac/GGIR/issues
License: Apache License (== 2.0) | file LICENSE
Suggests: testthat, covr, knitr, rmarkdown, actilifecounts, readxl
Imports: data.table, foreach, doParallel, signal, zoo, unisensR, ineq, methods, psych, irr, lubridate, GGIRread, ActCR, read.gt3x
Depends: stats, utils, R (≥ 3.5)
VignetteBuilder: knitr
NeedsCompilation: no
Packaged: 2025-04-25 07:19:01 UTC; vvanh
Author: Vincent T van Hees [aut, cre], Jairo H Migueles ORCID iD [aut], Severine Sabia [ctb], Matthew R Patterson [ctb], Zhou Fang [ctb], Joe Heywood [ctb], Joan Capdevila Pujol [ctb], Lena Kushleyeva [ctb], Mathilde Chen [ctb], Manasa Yerramalla [ctb], Patrick Bos ORCID iD [ctb], Taren Sanders [ctb], Chenxuan Zhao [ctb], Ian Meneghel Danilevicz ORCID iD [ctb], Victor Barreto Mesquita [ctb], Gaia Segantin [ctb], Medical Research Council UK [cph, fnd], Accelting [cph, fnd], French National Research Agency [cph, fnd]
Repository: CRAN
Date/Publication: 2025-04-25 09:10:01 UTC

A package to process multi-day raw accelerometer data

Description

Disclaimer: If you are a new GGIR user then please see the GGIR github-pages for a narrative overview of GGIR.

This document is primarily aimed at documenting the functions and their input arguments.

Please note that there is google discussion group for this package (link below).

You can thank us for sharing the code in this package and for developing it as a generic purpose tool by citing the package name and by citing the supporting publications (e.g. Migueles et al. 2019) in your publications.

Details

Package: GGIR
Type: Package
Version: 3.2-6
Date: 2025-04-25
License: Apache License (== 2.0)
Discussion group: https://groups.google.com/forum/#!forum/rpackageggir

Author(s)

References

Examples

  ## Not run: 
    #inspect file:
    I = g.inspectfile(datafile)

    #autocalibration:
    C = g.calibrate(datafile)

    #get meta-data:
    M = g.getmeta(datafile)
  
## End(Not run)
  data(data.getmeta)
  data(data.inspectfile)
  data(data.calibrate)

  #impute meta-data:
  IMP = g.impute(M = data.getmeta, I = data.inspectfile)
  #analyse and produce summary:
  A = g.analyse(I = data.inspectfile, C = data.calibrate, M = data.getmeta, IMP, ID = "01wk0")
  #plot data
  g.plot(IMP, M = data.getmeta, I = data.inspectfile, durplot=4)

Activity balance index (ABI)

Description

This function estimates the Activity balance index (ABI), which is a transformation of the self-similarity parameter (SSP), also known as scaling exponent or alpha.

Usage

  ABI(x)

Arguments

x

the estimated self-similarity parameter (SSP)

Details

ABI = exp(-abs(SSP-1)/exp(-2))

Value

The estimated Activity balance index (ABI) is a real number between zero and one.

Author(s)

Ian Meneghel Danilevicz <ian.meneghel-danilevicz@inserm.fr>

References

C.-K. Peng, S.V. Buldyrev, S. Havlin, M. Simons, H.E. Stanley, A.L. Goldberger Phys. Rev. E, 49 (1994), p. 1685 Mesquita, Victor & Filho, Florencio & Rodrigues, Paulo. (2020). Detection of crossover points in detrended fluctuation analysis: An application to EEG signals of patients with epilepsy. Bioinformatics. 10.1093/bioinformatics/btaa955.

Examples

  # Estimate Activity balance index of a very known time series
  # available on R base: the sunspot.year.
  ## Not run:   
    ssp = SSP(sunspot.year)
    abi = ABI(ssp)
  
## End(Not run)

Calculates Sleep Regularity Index

Description

Calculates Sleep Regularity Index per day pair proposed by Phillips and colleagues in 2017 expanded with day-pair level estimates.

Usage

  CalcSleepRegularityIndex(data = c(), epochsize = c(), desiredtz= c(),
                            SRI1_smoothing_wsize_hrs = NULL,
                            SRI1_smoothing_frac = NULL)

Arguments

data

Data.frame produced by function g.sib.det.

epochsize

Numeric value of epoch size in seconds.

desiredtz

See GGIR.

SRI1_smoothing_wsize_hrs

See GGIR.

SRI1_smoothing_frac

See GGIR.

Details

Calculates Sleep Regularity Index per day pair. Absense of missing data is not used as a criteria for calculation. Instead the code asses the fraction of the time for which matching valid data points were found in both days. Later in g.part4 this fraction is used to include or exclude days based on the excludenightcrit criteria it also uses for the other sleep variables. In g.report.part4 these day-level SRI values are stored, but also aggregated across all recording days, all weekend days, and all weekend days, respectively. Therefore, this function is broader in functionality than the algorithm proposed by Phillips and colleagues in 2017.

Value

Data.frame with columns: day (day number); Sleep Regularity Index, which by definition must lie in the range -100 (reversed regularity), to 0 (random pattern), to 100 (perfect regularity); weekday (e.g. Wednesday); frac_valid, number between 0 and 1 indicating the fraction of the 24 hour period for which valid data was available in both the current and the next day, and; date.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References


Detrended Fluctuation Analysis

Description

Detrended Fluctuation Analysis (DFA)

Usage

  DFA(data, scale = 2^(1/8), box_size = 4, m = 1)

Arguments

data

Univariate time series (must be a vector or data frame)

scale

Specifies the ratio between successive box sizes (by default scale = 2^(1/8))

box_size

Vector of box sizes (must be used in conjunction with scale = "F")

m

An integer of the polynomial order for the detrending (by default m=1)

Details

The DFA fluctuation can be computed in a geometric scale or for different choices of boxes sizes.

Value

Estimated alpha is a real number between zero and two.

Note

It is not possible estimating alpha for multiple time series at once.

Author(s)

Ian Meneghel Danilevicz <ian.meneghel-danilevicz@inserm.fr> Victor Barreto Mesquita <victormesquita40@hotmail.com>

References

C.-K. Peng, S.V. Buldyrev, S. Havlin, M. Simons, H.E. Stanley, A.L. Goldberger Phys. Rev. E, 49 (1994), p. 1685 Mesquita, Victor & Filho, Florencio & Rodrigues, Paulo. (2020). Detection of crossover points in detrended fluctuation analysis: An application to EEG signals of patients with epilepsy. Bioinformatics. 10.1093/bioinformatics/btaa955.

Examples

  # Estimate self-similarity of a very known time series available
  # on R base: the sunspot.year.
  # Then the spend time with each method is compared.
  ## Not run: 
    dfa = DFA(sunspot.year)
  
## End(Not run)

Shell function for analysing an accelerometer dataset.

Description

This function is designed to help users operate all steps of the analysis. It helps to generate and structure milestone data, and produces user-friendly reports. The function acts as a shell with calls to g.part1, g.part2, g.part3, g.part4 and g.part5.

Usage

GGIR(mode = 1:5,
     datadir = c(),
     outputdir = c(),
     studyname = c(),
     f0 = 1, f1 = 0,
     do.report = c(2, 4, 5, 6),
     configfile = c(),
     myfun = c(),
     verbose = TRUE, ...)

Arguments

mode

Numeric (default = 1:5). Specify which of the five parts need to be run, e.g., mode = 1 makes that g.part1 is run; or mode = 1:5 makes that the whole GGIR pipeline is run, from g.part1 to g.part5. Optionally mode can also include the number 6 to tell GGIR to run g.part6 which is currently under development.

datadir

Character (default = c()). Directory where the accelerometer files are stored, e.g., \"C:/mydata\", or list of accelerometer filenames and directories, e.g. c(\"C:/mydata/myfile1.bin\", \"C:/mydata/myfile2.bin\").

outputdir

Character (default = c()). Directory where the output needs to be stored. Note that this function will attempt to create folders in this directory and uses those folder to keep output.

studyname

Character (default = c()). If the datadir is a folder, then the study will be given the name of the data directory. If datadir is a list of filenames then the studyname as specified by this input argument will be used as name for the study.

f0

Numeric (default = 1). File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order.

f1

Numeric (default = 0). File index to finish with (defaults to number of files available).

do.report

Numeric (default = c(2, 4, 5, 6)). For which parts to generate a summary spreadsheet: 2, 4, 5, and/or 6. Default is c(2, 4, 5, 6). A report will be generated based on the available milestone data. When creating milestone data with multiple machines it is advisable to turn the report generation off when generating the milestone data, value = c(), and then to merge the milestone data and turn report generation back on while setting overwrite to FALSE.

configfile

Character (default = c()). Configuration file previously generated by function GGIR. See details.

myfun

List (default = c()). External function object to be applied to raw data. See package vignette for detailed tutorial with examples on how to use the function embedding: https://wadpac.github.io/GGIR/articles/ExternalFunction.html

verbose

Boolean (default = TRUE). to indicate whether console message should be printed. Note that warnings and error are always printed and can be suppressed with suppressWarning() or suppressMessages().

...

Any of the parameters used GGIR. Given the large number of parameters used in GGIR we have grouped them in objects that start with \"params_\". These are documented in the details section. You cannot provide these objects as argument to function GGIR, but you can provide the parameters inside them as input to function GGIR.

Details

Once you have used function GGIR and the output directory (outputdir) will be filled with milestone data and results. Function GGIR stores all the explicitely entered argument values and default values for the argument that are not explicitely provided in a csv-file named config.csv stored in the root of the output folder. The config.csv file is accepted as input to GGIR with argument configfile to replace the specification of all the arguments, except datadir and outputdir.

The practical value of this is that it eases the replication of analysis, because instead of having to share you R script, sharing your config.csv file will be sufficient. Further, the config.csv file contribute to the reproducibility of your data analysis.

Note: When combining a configuration file with explicitely provided argument values, the explicitely provided argument values will overrule the argument values in the configuration file. If a parameter is neither provided via the configuration file nor as input then GGIR uses its default paramter values which can be inspected with command print(load_params()), and if you are specifically interested in a certain subgroup of parameters, e.g., physical activity, then you can do print(load_params()$params_phyact). These defaults are part of the GGIR code and cannot be changed by the user.

The parameters that can be used in GGIR are:

params_general

A list of parameters used across all GGIR parts that do not fall in any of the other categories.

overwrite

Boolean (default = FALSE). Do you want to overwrite analysis for which milestone data exists? If overwrite = FALSE, then milestone data from a previous analysis will be used if available and visual reports will not be created again.

dayborder

Numeric (default = 0). Hour at which days start and end (dayborder = 4 would mean 4 am).

do.parallel

Boolean (default = TRUE). Whether to use multi-core processing (only works if at least 4 CPU cores are available).

maxNcores

Numeric (default = NULL). Maximum number of cores to use when argument do.parallel is set to true. GGIR by default uses either the maximum number of available cores or the number of files to process (whichever is lower), but this argument allows you to set a lower maximum.

acc.metric

Character (default = \"ENMO\"). Which one of the acceleration metrics do you want to use for all acceleration magnitude analyses in GGIR part 5 and the visual report? For example: \"ENMO\", \"LFENMO\", \"MAD\", \"NeishabouriCount_y\", or \"NeishabouriCount_vm\". Only one acceleration metric can be specified and the selected metric needs to have been calculated in part 1 (see g.part1) via arguments such as do.enmo = TRUE or do.mad = TRUE.

part5_agg2_60seconds

Boolean (default = FALSE). Whether to use aggregate epochs to 60 seconds as part of the GGIR g.part5 analysis. Aggregation is doen by averaging. Note that when working with count metrics such as Neishabouri counts this means that the threshold can stay the same as in part 2, because again the threshold is expressed relative to the original epoch size, even if averaged per minute. For example if we want to use a cut-point 100 count per minute then we specify mvpathreshold = 100 * (5/60) as well as 'threshold.mod = 100 * (5/60) regardless of whether we set part5_agg2_60seconds to TRUE or FALSE.

print.filename

Boolean (default = FALSE). Whether to print the filename before analysing it (in case do.parallel = FALSE). Printing the filename can be useful to investigate problems (e.g., to verify that which file is being read).

desiredtz

Character (default = \"\", i.e., system timezone). Timezone in which device was configured and experiments took place. If experiments took place in a different timezone, then use this argument for the timezone in which the experiments took place and argument configtz to specify where the device was configured. Use the \"TZ identifier\" as specified at https://en.wikipedia.org/wiki/Zone.tab to set desiredtz, e.g., \"Europe/London\".

configtz

Character (default = \"\", i.e., system timezone). At the moment only functional for GENEActiv .bin, AX3 cwa, ActiGraph .gt3x, and ad-hoc csv file format. Timezone in which the accelerometer was configured. Only use this argument if the timezone of configuration and timezone in which recording took place are different. Use the \"TZ identifier\" as specified at https://en.wikipedia.org/wiki/Zone.tab to set configtz, e.g., \"Europe/London\".

sensor.location

Character (default = \"wrist\"). To indicate sensor location, default is wrist. If it is hip, the HDCZA algorithm for sleep detection also requires longitudinal axis of sensor to be between -45 and +45 degrees.

windowsizes

Numeric vector, three values (default = c(5, 900, 3600)). To indicate the lengths of the windows as in c(window1, window2, window3): window1 is the short epoch length in seconds, by default 5, and this is the time window over which acceleration and angle metrics are calculated; window2 is the long epoch length in seconds for which non-wear and signal clipping are defined, default 900 (expected to be a multitude of 60 seconds); window3 is the window length of data used for non-wear detection and by default 3600 seconds. So, when window3 is larger than window2 we use overlapping windows, while if window2 equals window3 non-wear periods are assessed by non-overlapping windows.

idloc

Numeric (default = 1). If idloc = 1 the code assumes that ID number is stored in the obvious header field. Note that for ActiGraph data the ID is never stored in the file header. For value set to 2, 5, 6, and 7, GGIR looks at the filename and extracts the character string preceding the first occurance of a \"_\" (idloc = 2), \" \" (space, idloc = 5), \".\" (dot, idloc = 6), and \"-\" (idloc = 7), respectively. You may have noticed that idloc 3 and 4 are skipped, they were used for one study in 2012, and not actively maintained anymore, but because it is legacy code not omitted.

expand_tail_max_hours

Numeric (default = NULL). This parameter has been replaced by recordingEndSleepHour.

recordingEndSleepHour

Numeric (default = NULL). Time (in hours) at which the recording should end (or later) to expand the g.part1 output with synthetic data to trigger sleep detection for last night. Using argument recordingEndSleepHour implies the assumption that the participant fell asleep at or before the end of the recording if the recording ended at or after recordingEndSleepHour hour of the last day. This assumption may not always hold true and should be used with caution. The synthetic data for metashort entails: timestamps continuing regularly, zeros for acceleration metrics other than EN, one for EN. Angle columns are created in a way that it triggers the sleep detection using the equation: round(sin((1:length_expansion) / (900/epochsize))) * 15. To keep track of the tail expansion g.part1 stores the length of the expansion in the RData files, which is then passed via g.part2, g.part3, and g.part4 to g.part5. In g.part5 the tail expansion size is included as an additional variable in the csv-reports. In the g.part4 csv-report the last night is omitted, because we know that sleep estimates from the last night will not be trustworthy. Similarly, in the g.part5 output columns related to the sleep assessment will be omitted for the last window to avoid biasing the averages. Further, the synthetic data are also ignored in the visualizations and time series output to avoid biased output.

dataFormat

Character (default = \"raw\"). To indicate what the format is of the data in datadir. Alternatives: ukbiobank_csv, actiwatch_csv, actiwatch_awd, actigraph_csv, sensewear_xls, phb_xlsx, and fitbit_json which correspond to epoch level data files from, respecitively, UK Biobank in csv format, Actiwatch in csv format, Actiwatch in awd format, ActiGraph csv format, Sensewear in xls format (also works with xlsx), Philips Health Band in xlsx format, and Fitbit in json format. Here, the assumed epoch size for UK Biobank csvdata is 5 seconds. The epoch size for the other non-raw data formats is flexible, but make sure that you set first value of argument windowsizes accordingly. Also when working with non-raw data formats specify argument extEpochData_timeformat as documented below. For ukbiobank_csv nonwear is a column in the data itself, for actiwatch_csv, actiwatch_awd, actigraph_csv, and sensewear_xls non-wear is detected as 60 minute rolling zeros. The length of this window can be modified with the third value of argument windowsizes expressed in seconds.

maxRecordingInterval

Numeric (default = NULL). To indicate the maximum gap in hours between repeated measurements with the same ID for the recordings to be appended. So, the assumption is that the ID can be matched, make sure argument idloc is set correctly. If argument maxRecordingInterval is set to NULL (default) recordings are not appended. If recordings overlap then GGIR will use the data from the latest recording. If recordings are separated then the timegap between the recordings is filled with data points that resemble monitor not worn. The maximum value of maxFile gap is 504 (21 days). Only recordings from the same accelerometer brand are appended. This functionality is applied after all other aspect of GGIR part 1 are completed for all input files. The part 2 csv report will show number of appended recordings, sampling rate for each, time overlap or gap and the names of the filenames of the respective recording.

recording_split_times

Character (default = NULL). To indicate path to a csv file with a column that has ID in the column name that holds the participant IDs, followed by columns with either dates or full timestamps on which the recording should be split. Here, timestamp format is specified with parameter recording_split_timeformat. The names of these columns are used to refer to each resulting segment. To prevent extremely long file name GGIR ignores spaces and does not consider more than 10 characters which are forced to lower case. If the recording starts before or ends after the first and last split time then the start and/or end of the recording is also used as split time and referred to as startrec and endrec, respectively. Files are split after all other aspect of GGIR part 1 are completed for all input files.

recording_split_timeformat

Character (default = \"%d/%m/%Y %H:%M\") To indicate timestamp format as used in file as specified with recording_split_times. For guidance on how to specify time formats in R see: https://wadpac.github.io/GGIR/articles/DateTimeFormatsInR.html.

recording_split_ignore_edges

Boolean (default = FALSE) To indicate whether the recording time before and after the time range defined by recording_split_times should be considered as segments.

recording_split_overlap

Numeric (default = 0). Number of hours to use as buffer when splitting recording. A possitive number means that the split recordings overlap, a nevative number indicates a gap.

extEpochData_timeformat

Character (default = \"%d-%m-%Y %H:%M:%S\"). To specify the time format used in the external epoch level data when argument dataFormat is set to \"actiwatch_csv\", \"actiwatch_awd\", \"actigraph_csv\" or \"sensewear_xls\". For example \"%Y-%m-%d %I:%M:%S %p\" for \"2023-07-11 01:24:01 PM\" or \"%m/%d/%Y %H:%M:%S\" \"2023-07-11 13:24:01\". For guidance on how to specify time formats in R see: https://wadpac.github.io/GGIR/articles/DateTimeFormatsInR.html.

params_rawdata

A list of parameters used to related to reading and pre-processing raw data, excluding parameters related to metrics as those are in the params_metrics object.

backup.cal.coef

Character (default = \"retrieve\"). Option to use backed-up calibration coefficient instead of deriving the calibration coefficients when analysing the same file twice. Argument backup.cal.coef has two usecase. Use case 1: If the auto-calibration fails then the user has the option to provide back-up calibration coefficients via this argument. The value of the argument needs to be the name and directory of a csv-spreadsheet with the following column names and subsequent values: \"filename\" with the names of accelerometer files on which the calibration coefficients need to be applied in case auto-calibration fails; \"scale.x\", \"scale.y\", and \"scale.z\" with the scaling coefficients; \"offset.x\", \"offset.y\", and \"offset.z\" with the offset coefficients, and; \"temperature.offset.x\", \"temperature.offset.y\", and \"temperature.offset.z\" with the temperature offset coefficients. This can be useful for analysing short lasting laboratory experiments with insufficient sphere data to perform the auto-calibration, but for which calibration coefficients can be derived in an alternative way. It is the users responsibility to compile the csv-spreadsheet. Instead of building this file the user can also Use case 2: The user wants to avoid performing the auto-calibration repeatedly on the same file. If backup.cal.coef value is set to \"retrieve\" (default) then GGIR will look out for the \"data_quality_report.csv\" file in the outputfolder QC, which holds the previously generated calibration coefficients. If you do not want this happen, then deleted the data_quality_report.csv from the QC folder or set it to value \"redo\".

minimumFileSizeMB

Numeric (default = 2). Minimum File size in MB required to enter processing. This argument can help to avoid having short uninformative files to enter the analyses. Given that a typical accelerometer collects several MBs per hour, the default setting should only skip the very tiny files.

do.cal

Boolean (default = TRUE). Whether to apply auto-calibration or not by g.calibrate. Recommended setting is TRUE.

imputeTimegaps

Boolean (default = TRUE). To indicate whether timegaps larger than 1 sample should be imputed. Currently only used for .gt3x data and ActiGraph .csv format, where timegaps can be expected as a result of Actigraph's idle sleep.mode configuration.

spherecrit

Numeric (default = 0.3). The minimum required acceleration value (in g) on both sides of 0 g for each axis. Used to judge whether the sphere is sufficiently populated

minloadcrit

Numeric (default = 168). The minimum number of hours the code needs to read for the autocalibration procedure to be effective (only sensitive to multitudes of 12 hrs, other values will be ceiled). After loading these hours only extra data is loaded if calibration error has not been reduced to under 0.01 g.

printsummary

Boolean (default = FALSE). If TRUE will print a summary of the calibration procedure in the console when done.

chunksize

Numeric (default = 1). Value to specify the size of chunks to be loaded as a fraction of an approximately 12 hour period for auto-calibration procedure and as fraction of 24 hour period for the metric calculation, e.g., 0.5 equals 6 and 12 hour chunks, respectively. For machines with less than 4Gb of RAM memory or with < 2GB memory per process when using do.parallel = TRUE a value below 1 is recommended. The value is constrained by GGIR to not be lower than 0.05. Please note that setting 0.05 will not produce output when 3rd value of parameter windowsizes is 3600.

dynrange

Numeric (default = NULL). Provide dynamic range of 8 gravity.

interpolationType

Integer (default = 1). To indicate type of interpolation to be used when resampling time series (mainly relevant for Axivity and Parmay Matrix sensors), 1=linear, 2=nearest neighbour.

rmc.file

Character (default = NULL). Filename of file to be read if it is in the working directory, or full path to the file otherwise.

rmc.nrow

Numeric (default = NULL). Number of rows to read, same as nrow argument in read.csv and nrows in fread. The whole file is read by default (i.e., rmc.nrow = Inf).

rmc.skip

Numeric (default = 0). Number of rows to skip, same as skip argument in read.csv and in fread.

rmc.dec

Character (default = \".\"). Decimal used for numbers, same as dec argument in read.csv and in fread.

rmc.firstrow.acc

Numeric (default = NULL). First row (number) of the acceleration data.

rmc.firstrow.header

Numeric (default = NULL). First row (number) of the header. Leave blank if the file does not have a header.

rmc.header.length

Numeric (default = NULL). If file has header, specify header length (number of rows).

rmc.col.acc

Numeric, three values (default = c(1, 2, 3)). Vector with three column (numbers) in which the acceleration signals are stored.

rmc.col.temp

Numeric (default = NULL). Scalar with column (number) in which the temperature is stored. Leave in default setting if no temperature is available. The temperature will be used by g.calibrate.

rmc.col.time

Numeric (default = NULL). Scalar with column (number) in which the timestamps are stored. Leave in default setting if timestamps are not stored.

rmc.unit.acc

Character (default = \"g\"). Character with unit of acceleration values: \"g\", \"mg\", or \"bit\".

rmc.unit.temp

Character (default = \"C\"). Character with unit of temperature values: (K)elvin, (C)elsius, or (F)ahrenheit.

rmc.unit.time

Character (default = \"POSIX\"). Character with unit of timestamps: \"POSIX\", \"UNIXsec\" (seconds since origin, see argument rmc.origin), \"UNIXmsec\" (same as UNIXsec but in milliseconds), \"character\", or \"ActivPAL\" (exotic timestamp format only used in the ActivPAL activity monitor).

rmc.format.time

Character (default = \"%Y-%m-%d %H:%M:%OS\"). Character giving a date-time format as used by strptime. Only used for rmc.unit.time: character and POSIX.. For guidance on how to specify time formats in R see: https://wadpac.github.io/GGIR/articles/DateTimeFormatsInR.html

rmc.bitrate

Numeric (default = NULL). If unit of acceleration is a bit then provide bit rate, e.g., 12 bit.

rmc.dynamic_range

Numeric or character (default = NULL). If unit of acceleration is a bit then provide dynamic range deviation in g from zero, e.g., +/-6g would mean this argument needs to be 6. If you give this argument a character value the code will search the file header for elements with a name equal to the character value and use the corresponding numeric value next to it as dynamic range.

rmc.unsignedbit

Boolean (default = TRUE). If unsignedbit = TRUE means that bits are only positive numbers. if unsignedbit = FALSE then bits are both positive and negative.

rmc.origin

Character (default = \"1970-01-01\"). Origin of time when unit of time is UNIXsec, e.g., 1970-1-1.

rmc.desiredtz

Character (default = NULL). Timezone in which experiments took place. This argument is scheduled to be deprecated and is now used to overwrite desiredtz if not provided.

rmc.configtz

Character (default = NULL). Timezone in which device was configured. This argument is scheduled to be deprecated and is now used to overwrite configtz if not provided.

rmc.sf

Numeric (default = NULL). Sample rate in Hertz, if this is stored in the file header then that will be used instead (see argument rmc.headername.sf).

rmc.headername.sf

Character (default = NULL). If file has a header: Row name under which the sample frequency can be found.

rmc.headername.sn

Character (default = NULL). If file has a header: Row name under which the serial number can be found.

rmc.headername.recordingid

Character (default = NULL). If file has a header: Row name under which the recording ID can be found.

rmc.header.structure

Character (default = NULL). Used to split the header name from the header value, e.g., \":\" or \" \".

rmc.check4timegaps

Boolean (default = FALSE). To indicate whether gaps in time should be imputed with zeros. Some sensing equipment provides accelerometer with gaps in time. The rest of GGIR is not designed for this, by setting this argument to TRUE the gaps in time will be filled with zeros.

rmc.col.wear

Numeric (default = NULL). If external wear detection outcome is stored as part of the data then this can be used by GGIR. This argument specifies the column in which the wear detection (Boolean) is stored.

rmc.doresample

Boolean (default = FALSE). To indicate whether to resample the data based on the available timestamps and extracted sample rate from the file header.

rmc.noise

Numeric (default = 13). Noise level of acceleration signal in mg-units, used when working ad-hoc .csv data formats using read.myacc.csv. The read.myacc.csv does not take rmc.noise as argument, but when interacting with GGIR or g.part1 rmc.noise is used.

rmc.scalefactor.acc

Numeric value (default 1) to scale the acceleration signals via multiplication. For example, if data is provided in m/s2 then by setting this to 1/9.81 we would derive gravitational units.

frequency_tol

Number (default = 0.1) as passed on to readAxivity from the GGIRread package. Represents the frequency tolerance as fraction between 0 and 1. When the relative bias per data block is larger than this fraction then the data block will be imputed by lack of movement with gravitational oriationed guessed from most recent valid data block. Only applicable to Axivity .cwa data.

nonwear_range_threshold

Numeric (default 150) used to define maximum value range per axis for non-wear detection, used in combination with brand specific standard deviation per axis.

params_metrics

A list of parameters used to specify the signal metrics that need to be extract in GGIR g.part1.

do.anglex

Boolean (default = FALSE). If TRUE, calculates the angle of the X axis relative to the horizontal:

angleX = (\tan{^{-1}\frac{acc_{rollmedian(x)}}{(acc_{rollmedian(y)})^2 + (acc_{rollmedian(z)})^2}}) * 180/\pi

do.angley

Boolean (default = FALSE). If TRUE, calculates the angle of the Y axis relative to the horizontal:

angleY = (\tan{^{-1}\frac{acc_{rollmedian(y)}}{(acc_{rollmedian(x)})^2 + (acc_{rollmedian(z)})^2}}) * 180/\pi

do.anglez

Boolean (default = TRUE). If TRUE, calculates the angle of the Z axis relative to the horizontal:

angleZ = (\tan{^{-1}\frac{acc_{rollmedian(z)}}{(acc_{rollmedian(x)})^2 + (acc_{rollmedian(y)})^2}}) * 180/\pi

do.zcx

Boolean (default = FALSE). If TRUE, calculates metric zero-crossing count for x-axis. For computation specifics see source code of function g.applymetrics

do.zcy

Boolean (default = FALSE). If TRUE, calculates metric zero-crossing count for y-axis. For computation specifics see source code of function g.applymetrics

do.zcz

Boolean (default = FALSE). If TRUE, calculates metric zero-crossing count for z-axis. For computation specifics see source code of function g.applymetrics

do.enmo

Boolean (default = TRUE). If TRUE, calculates the metric:

ENMO = \sqrt{acc_x^2 + acc_y^2 + acc_z^2} - 1

(if ENMO < 0, then ENMO = 0).

do.lfenmo

Boolean (default = FALSE). If TRUE, calculates the metric ENMO over the low-pass filtered accelerations (for computation specifics see source code of function g.applymetrics). The filter bound is defined by the parameter hb.

do.en

Boolean (default = FALSE). If TRUE, calculates the Euclidean Norm of the raw accelerations:

EN = \sqrt{acc_x^2 + acc_y^2 + acc_z^2}

do.mad

Boolean (default = FALSE). If TRUE, calculates the Mean Amplitude Deviation:

MAD = \frac{1}{n}\Sigma|r_i - \overline{r}|

do.enmoa

Boolean (default = FALSE). If TRUE, calculates the metric:

ENMOa = \sqrt{acc_x^2 + acc_y^2 + acc_z^2} - 1

(if ENMOa < 0, then ENMOa = |ENMOa|).

do.roll_med_acc_x

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.roll_med_acc_y

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.roll_med_acc_z

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.dev_roll_med_acc_x

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.dev_roll_med_acc_y

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.dev_roll_med_acc_z

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.bfen

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.hfen

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.hfenplus

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.lfen

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.lfx

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.lfy

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.lfz

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.hfx

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.hfy

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.hfz

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.bfx

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.bfy

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.bfz

Boolean (default = FALSE). If TRUE, calculates the metric. For computation specifics see source code of function g.applymetrics.

do.brondcounts

Boolean (default = FALSE). this option has been deprecated (October 2022) due to issues with the activityCounts package that we used as a dependency. If TRUE, calculated the metric via R package activityCounts. We called them BrondCounts because there are large number of activity counts in the physical activity and sleep research field. By calling them _brondcounts_ we clarify that these are the counts proposed by Jan Br&#248;nd and implemented in R by Ruben Brondeel. The _brondcounts_ are intended to be an imitation of the counts produced by one of the closed source ActiLife software by ActiGraph.

do.neishabouricounts

Boolean (default = FALSE). If TRUE, calculates the metric via R package actilifecounts, which is an implementation of the algorithm used in the closed-source software ActiLife by ActiGraph (methods published in doi: 10.1038/s41598-022-16003-x). We use the name of the first author (instead of ActiLifeCounts) of the paper and call them NeishabouriCount under the uncertainty that ActiLife will implement this same algorithm over time. To use the Neishabouri counts for the physical activity intensity classification in part 5 (i.e., metric over the threshold.lig, threshold.mod, and threshold.vig would be applied), the acc.metric argument needs to be set as one of the following: \"NeishabouriCount_x\", \"NeishabouriCount_y\", \"NeishabouriCount_z\", \"NeishabouriCount_vm\" to use the counts in the x-, y-, z-axis or vector magnitude, respectively.

lb

Numeric (default = 0.2). Lower boundary of the frequency filter (in Hertz) as used in the filter-based metrics.

hb

Numeric (default = 15). Higher boundary of the frequency filter (in Hertz) as used in the filter-based metrics.

n

Numeric (default = n). Order of the frequency filter as used in the filter-based metrics.

zc.lb

Numeric (default = 0.25). Used for zero-crossing counts only. Lower boundary of cut-off frequency filter.

zc.hb

Numeric (default = 3). Used for zero-crossing counts only. Higher boundary of cut-off frequencies in filter.

zc.sb

Numeric (default = 0.01). Stop band used for calculation of zero crossing counts. Value is the acceleration threshold in g units below which acceleration will be rounded to zero.

zc.order

Numeric (default = 2). Used for zero-crossing counts only. Order of frequency filter.

zc.scale

Numeric (default = 1) Used for zero-crossing counts only. Scaling factor to be applied after counts are calculated (GGIR part 3).

actilife_LFE

Boolean (default = FALSE). If TRUE, calculates the NeishabouriCount metric with the low-frequency extension filter as proposed in the closed source ActiLife software by ActiGraph. Only applicable to the metric NeishabouriCount.

params_cleaning

A list of parameters used across all GGIR parts releated to masking or imputing data, abbreviated as \"cleaning\".

do.imp

Boolean (default = TRUE). Whether to impute missing values (e.g., suspected of monitor non-wear or clippling) or not by g.impute in GGIR g.part2. Recommended setting is TRUE.

TimeSegments2ZeroFile

Character (default = NULL). Takes path to a csv file that has columns \"windowstart\" and \"windowend\" to refer to the start and end time of a time windows in format \"2024-10-12 20:00:00\", and \"filename\" of the GGIR milestone data file without the \"meta_\" segment of the name. GGIR part 2 uses this to set all acceleration values to zero and the non-wear classification to zero (meaning sensor worn). Motivation: When the accelerometer is not worn during the night GGIR automatically labels them as invalid, while the user may like to treat them as zero movement. Disclaimer: This functionality was developed in 2019. With hindsight it is not generic enough and in need for revision. Please contact GGIR maintainers if you would like us to invest time in improving this functionality.

data_cleaning_file

Character (default = NULL). Optional path to a csv file you create that holds four columns: ID, day_part5, relyonguider_part4, and night_part4. ID should hold the participant ID. Columns day_part5 and night_part4 allow you to specify which day(s) and night(s) need to be excluded from g.part5 and g.part4, respectively. When including multiple day(s)/night(s) create a new line for each day/night. So, this will be done regardless of whether the rest of GGIR thinks those day(s)/night(s) are valid. Column relyonguider_part4 allows you to specify for which nights g.part4 should fully rely on the guider. See also package vignette.

excludefirstlast.part5

Boolean (default = FALSE). If TRUE then the first and last window (waking-waking, midnight-midnight, or sleep onset-onset) are ignored in g.part5.

excludefirstlast

Boolean (default = FALSE). If TRUE then the first and last night of the measurement are ignored for the sleep assessment in g.part4.

excludefirst.part4

Boolean (default = FALSE). If TRUE then the first night of the measurement are ignored for the sleep assessment in g.part4.

excludelast.part4

Boolean (default = FALSE). If TRUE then the last night of the measurement are ignored for the sleep assessment in g.part4.

includenightcrit

Numeric (default = 16). Minimum number of valid hours per night (24 hour window between noon and noon), used for sleep assessment in g.part4.

minimum_MM_length.part5

Numeric (default = 23). Minimum length in hours of a MM day to be included in the cleaned g.part5 results.

study_dates_file

Character (default = c()). Full path to csv file containing the first and last date of the expected wear period for every study participant (dates are provided per individual). Expected format of the activity diary is: First column headers followed by one row per recording. There should be three columns: first column is recording ID, which needs to match with the ID GGIR extracts from the accelerometer file; second column should contain the first date of the study; and third column the last date of the study. Date columns should be by default in format \"23-04-2017\", or in the date format specified by argument study_dates_dateformat (below). If not specified (default), then GGIR would use the first and last day of the recording as beginning and end of the study. Note that these dates are used on top of the data_masking_strategy selected.

study_dates_dateformat

Character (default = \"%d-%m-%Y\"). To specify the date format used in the study_dates_file as used by strptime. For guidance on how to specify time formats in R see: https://wadpac.github.io/GGIR/articles/DateTimeFormatsInR.html

strategy

Deprecated and replaced by data_masking_strategy. If strategy is specified then its value is passed on and used for data_masking_strategy.

data_masking_strategy

Numeric (default = 1). How to deal with knowledge about study protocol. data_masking_strategy = 1 means select data based on hrs.del.start and hrs.del.end. data_masking_strategy = 2 makes that only the data between the first midnight and the last midnight is used. data_masking_strategy = 3 selects the most active X days in the file where X is specified by argument ndayswindow, where the days are a series of 24-h blocks starting any time in the day (X hours at the beginning and end of this period can be deleted with arguments hrs.del.start and hrs.del.end) data_masking_strategy = 4 to only use the data after the first midnight. data_masking_strategy = 5 is similar to data_masking_strategy = 3, but it selects X complete calendar days where X is specified by argument ndayswindow (X hours at the beginning and end of this period can be deleted with arguments hrs.del.start and hrs.del.end).

hrs.del.start

Numeric (default = 0). How many HOURS after start of experiment did wearing of monitor start? Used in GGIR g.part2 when data_masking_strategy = 1.

hrs.del.end

Numeric (default = 0). How many HOURS before the end of the experiment did wearing of monitor definitely end? Used in GGIR g.part2 when data_masking_strategy = 1.

maxdur

Numeric (default = 0). How many DAYS after start of experiment did experiment definitely stop? (set to zero if unknown).

ndayswindow

Numeric (default = 7). If data_masking_strategy is set to 3 or 5, then this is the size of the window as a number of days. For data_masking_strategy 3 value can be fractional, e.g. 7.5, while for data_masking_strategy 5 it needs to be an integer.

includedaycrit.part5

Numeric (default = 2/3). Inclusion criteria used in part 5 for number of valid hours during the waking hours of a day, when value is smaller than or equal to 1 used as fraction of waking hours, when value above 1 used as absolute number of valid hours required. Do not confuse this argument with argument includedaycrit which is only used in GGIR part 2 and applies to the entire day.

includenightcrit.part5

Numeric (default = 0). Inclusion criteria used in part 5 for number of valid hours during the sleep period hours of a day (the night), when value is smaller than or equal to 1 used as fraction of sleep period hours, when value above 1 used as absolute number of valid hours required. Do not confuse this argument with argument includenightcrit which is only used in GGIR part 4 and applies to the entire 24 hour window from noon to noon or 6pm to 6pm.

segmentWEARcrit.part5

Numeric (default = 0.5). Fraction of qwindow segment expected to be valid in part 5, where 0.3 indicates that at least 30 percent of the time should be valid.

segmentDAYSPTcrit.part5

Numeric vector or length 2 (default = c(0.9, 0)). Inclusion criteria for the proportion of the segment that should be classified as day (awake) and spt (sleep period time) to be considered valid. If you are interested in comparing time spent in behaviour then it is better to set one of the two numbers to 0, and the other defines the proportion of the segment that should be classified as day or spt, respectively. The default setting would focus on waking hour segments and includes all segments that overlap for at least 90 percent with waking hours. In order to shift focus to the SPT you could use c(0, 0.9) which ensures that all segments that overlap for at least 90 percent with the SPT are included. Setting both to zero would be problematic when comparing time spent in behaviours between days or individuals: A complete segment would be averaged with an incomplete segments (someone going to bed or waking up in the middle of a segment) by which it is no longer clear whether the person is less active or sleeps more during that segment. Similarly it is not clear whether the person has more wakefulness during SPT for a segment or woke up or went to bed during the segment.

includedaycrit

Numeric (default = 16). Minimum required number of valid hours in calendar day specific to analysis in part 2. If you specify two values as in c(16, 16) then the first value will be used in part 2 and the second value will be used in part 5 and applied as a criterion on the full part 5 window. Note that this is then applied in addition to parameter includedaycrit.part5 which only looks at valid data during waking hours.

max_calendar_days

Numeric (default = 0). The maximum number of calendar days to include (set to zero if unknown).

nonWearEdgeCorrection

Boolean (default = TRUE). If TRUE then the non-wear detection around the edges of the recording (first and last 3 hours) are corrected following description in vanHees2013 as has been the default since then. This functionality is advisable when working with sleep clinic or exercise lab data typically lasting less than a day.

nonwear_approach

Character (default = \"2023\"). Whether to use the traditional version of the non-wear detection algorithm (nonwear_approach = \"2013\") or the new version (nonwear_approach = \"2023\"). The 2013 version would use the longsize window (windowsizes[3], one hour as default) to check the conditions for nonwear identification and would flag as nonwear the mediumsize window (windowsizes[2], 15 min as default) in the middle. The 2023 version differs in which it would flag as nonwear the full longsize window. For the 2013 method the longsize window is centered in the centre of the mediumsize window, while in the 2023 method the longsizewindow is aligned with its left edge to the left edge of the mediumsize window.

includecrit.part6

Numeric (default = c(2/3, 2/3)) Vector of two with the minimum fraction of valid data required for day and spt time, respectively. This criteria is only used for circadian rhythm analysis.

nonwearFiltermaxHours

Numeric (default = NULL). If not NULL, ignore detected nonwear periods that last shorter than nonwearFiltermaxHours during a window as defined by parameter NonwearFilterWindow. If NonwearFilterWindow is not provided (set to NULL as is the default) check whether qwindow is defined as activity diary file and whether it has timestamps that allow for defining a time in bed, SPT or lightsoff window. For this the code looks for column names in the diary with the terms inbed, sleeponset, or lightsout to define the start of the window. Further, to define the end of the window the code looks for columns outbed, wakeup, or lightsoff. If yes, it uses the largest of the windows that can be defined with these timestamps. If not, use midnight-6am as fall back setting. You may realise that these columns are the same as the advanced format for the sleelog accepted by GGIR part 4. So, if you already have an advanced format sleeplog for part 4 then you can provide this as value for the qwindow parameter. If you want to use qwindow to guide the nonwear filtering as described in here but do not want GGIR to use it for day segment analysis in part 2 or 5 then make sure the diary filename includes the word \"onlyfilter\" or \"filteronly\" to tell GGIR to only use qwindow for nonwear filtering. The main purpose of this functionality is to offer the option to ignore short lasting nonwear episodes during the night when there is suspicion that these are falsely detect, e.g. in individuals with extended motionless sleep periods caused by medication.

nonwearFilterWindow

Numeric (default = NULL). Vector of length 2 to specify the start and end hour of the night to be used for the functionality as described above for NonwearFiltermaxHours.

params_phyact

A list of parameters releated to physical activity as used in GGIR g.part2 and GGIR g.part5.

mvpathreshold

Numeric (default = NULL). Legacy parameter, if not provided GGIR uses the value of threshold.mod for this. Acceleration threshold for MVPA estimation in GGIR g.part2. This can be a single number or an vector of numbers, e.g., mvpathreshold = c(100, 120). In the latter case the code will estimate MVPA separately for each threshold. If this variable is left blank, e.g., mvpathreshold = c(), then MVPA is not estimated.

mvpadur

Numeric (default = c(1, 5, 10)). The bout duration(s) for which MVPA will be calculated. Only used in GGIR g.part2.

boutcriter

Numeric (default = NULL). Legacy parameter, if not provided GGIR uses the value of boutcriter.mvpa for this. A number between 0 and 1, it defines what fraction of a bout needs to be above the mvpathreshold, only used in GGIR g.part2.

threshold.lig

Numeric (default = 40). In g.part5: Threshold for light physical activity to separate inactivity from light. Value can be one number or an vector of multiple numbers, e.g., threshold.lig =c(30,40). If multiple numbers are entered then analysis will be repeated for each combination of threshold values. Threshold is applied to the first metric in the milestone data, so if you have only specified do.enmo = TRUE then it will be applied to ENMO.

threshold.mod

Numeric (default = 100). In g.part5: Threshold for moderate physical activity to separate light from moderate. Value can be one number or an vector of multiple numbers, e.g., threshold.mod = c(100, 120). If multiple numbers are entered then analysis will be repeated for each combination of threshold values. Threshold is applied to the first metric in the milestone data, so if you have only specified do.enmo = TRUE then it will be applied to ENMO.

threshold.vig

Numeric (default = 400). In g.part5: Threshold for vigorous physical activity to separate moderate from vigorous. Value can be one number or an vector of multiple numbers, e.g., threshold.vig =c(400,500). If multiple numbers are entered then analysis will be repeated for each combination of threshold values. Threshold is applied to the first metric in the milestone data, so if you have only specified do.enmo = TRUE then it will be applied to ENMO.

boutdur.mvpa

Numeric (default = c(1, 5, 10)). Duration(s) of MVPA bouts in minutes to be extracted. It will start with the identification of the longest to the shortest duration. In the default setting, it will start with the 10 minute bouts, followed by 5 minute bouts in the rest of the data, and followed by 1 minute bouts in the rest of the data.

boutdur.in

Numeric (default = c(10, 20, 30)). Duration(s) of inactivity bouts in minutes to be extracted. Inactivity bouts are detected in the segments of the data which were not labelled as sleep or MVPA bouts. It will start with the identification of the longest to the shortest duration. In the default setting, it will start with the identification of 30 minute bouts, followed by 20 minute bouts in the rest of the data, and followed by 10 minute bouts in the rest of the data. Note that we use the term inactivity instead of sedentary behaviour for the lowest intensity level of behaviour. The reason for this is that GGIR does not attempt to classifying the activity type sitting at the moment, by which we feel that using the term sedentary behaviour would fail to communicate that.

boutdur.lig

Numeric (default = c(1, 5, 10)). Duration(s) of light activity bouts in minutes to be extracted. Light activity bouts are detected in the segments of the data which were not labelled as sleep, MVPA, or inactivity bouts. It will start with the identification of the longest to the shortest duration. In the default setting, this will start with the identification of 10 minute bouts, followed by 5 minute bouts in the rest of the data, and followed by 1 minute bouts in the rest of the data.

boutcriter.mvpa

Numeric (default = 0.8). A number between 0 and 1, it defines what fraction of a bout needs to be above the threshold.mod.

boutcriter.in

Numeric (default = 0.9). A number between 0 and 1, it defines what fraction of a bout needs to be below the threshold.lig.

boutcriter.lig

Numeric (default = 0.8). A number between 0 and 1, it defines what fraction of a bout needs to be between the threshold.lig and the threshold.mod.

frag.metrics

Character (default = NULL). Fragmentation metric to extract. Can be \"mean\", \"TP\", \"Gini\", \"power\", or \"CoV\", \"NFragPM\", or all the above metrics with \"all\". See package vignette for description of fragmentation metrics.

part6_threshold_combi

Character (default = NULL) to indicate the threshold combination derived in part 5 to be used for part 6. For example, \"40_100_120\". If left in default value GGIR will use the first threshold value from parameters threshold.lig, threshold.mod, and threshold.vig.

bout.metric

Deprecated parameter that was previously used to choose which bout detection metric (algorithm) GGIR should use. GGIR now uses only one algorithm.

params_sleep

A list of parameters used to configure the sleep analysis as performend in GGIR g.part3 and g.part4.

relyonguider

Boolean (default = FALSE). Sustained inactivity bouts (sib) that overlap with the guider are labelled as sleep. If relyonguider = FALSE and the sib overlaps only partially with the guider then it is the sib that defines the edge of the SPT window and not the guider. If relyonguider = TRUE and the sib overlaps only partially with the guider then it is the guider that defines the edge of the SPT window and not the sib. If participants were instructed NOT to wear the accelerometer during waking hours and ignorenonware=FALSE then set to relyonguider=TRUE, in all other scenarios set to FALSE.

relyonsleeplog

Boolean (default = FALSE). Do not use, now replaced by argument relyonguider. Values provided to argument relyonsleeplog will be passed on to argument relyonguider to not preserve functionality of old R scripts.

def.noc.sleep

Numeric (default = 1). The time window during which sustained inactivity will be assumed to represent sleep, e.g., def.noc.sleep = c(21, 9). This is only used if no sleep log entry is available. If left blank def.noc.sleep = c() then the 12 hour window centred at the least active 5 hours of the 24 hour period will be used instead. Here, L5 is hardcoded and will not change by changing argument winhr in function g.part2. If def.noc.sleep is filled with a single integer, e.g., def.noc.sleep=c(1) then the window will be detected with based on built in algorithms. See argument HASPT.algo from HASPT for specifying which of the algorithms to use.

sleepwindowType

Character (default = \"SPT\"). To indicate type of information in the sleeplog, \"SPT\" for sleep period time. Set to \"TimeInBed\" if sleep log recorded time in bed to enable calculation of sleep latency and sleep efficiency.

nnights

Numeric (default = NULL). This argument has been deprecated.

loglocation

Character (default = NULL). Path to csv file with sleep log information. See package vignette for how to format this file.

colid

Numeric (default = 1). Column number in the sleep log spreadsheet in which the participant ID code is stored.

coln1

Numeric (default = 2). Column number in the sleep log spreadsheet where the onset of the first night starts.

ignorenonwear

Boolean (default = TRUE). If TRUE then ignore detected monitor non-wear periods to avoid confusion between monitor non-wear time and sustained inactivity.

constrain2range

Deprecated, used to be a Boolean (default = TRUE) Whether or not to constrain the range of threshold used in the diary free sleep period time window detection.

HASPT.algo

Character (default = \"HDCZA\"). To indicate what algorithm should be used for the sleep period time detection. Default \"HDCZA\" is Heuristic algorithm looking at Distribution of Change in Z-Angle as described in van Hees et al. 2018. Other options included: \"HorAngle\", which is based on HDCZA but replaces non-movement detection of the HDCZA algorithm by looking for time segments where the angle of the longitudinal sensor axis has an angle relative to the horizontal plane between -45 and +45 degrees. And \"NotWorn\" which is also the same as HDCZA but looks for time segments when a rolling average of acceleration magnitude is below 5 per cent of its standard deviation, see Cookbook vignette in the Annexes of https://wadpac.github.io/GGIR/ for more detailed guidance on how to use \"NotWorn\".

HDCZA_threshold

Numeric (default = c()) If HASPT.algo is set to \"HDCZA\" and HDCZA_threshold is NOT NULL, (e.g., HDCZA_threshold = 0.2), then that value will be used as threshold in the 6th step in the diagram of Figure 1 in van Hees et al. 2018 Scientific Report (doi: 10.1038/s41598-018-31266-z). However, doing so has not been supported by research yet and is only intended to facilitate methodological research, so we advise sticking with the default in line with the publication. Further, if HDCZA_threshold is set to a numeric vector of length 2, e.g. c(10, 15), that will be used as percentile and multiplier for the above mentioned 6th step.

HASPT.ignore.invalid

Boolean (default = FALSE). To indicate whether invalid time segments should be ignored in the heuristic guiders. If FALSE (default), the imputed angle or activity metric during the invalid time segments are used. If TRUE, invalid time segments are ignored (i.e., they cannot contribute to the guider). If NA, then invalid time segments are considered to be no movement segments and can contribute to the guider. Further, the guider name in the output will be shown with \"+invalid\" its end, e.g. \"HDCZA+invalid\", to reflect the NA setting. When HASPT.algo is \"NotWorn\", HASPT.ignore.invalid is automatically set to NA.

HASIB.algo

Character (default = \"vanHees2015\"). To indicate which algorithm should be used to define the sustained inactivity bouts (i.e., likely sleep). Options: \"vanHees2015\", \"Sadeh1994\", \"Galland2012\", \"NotWorn\", \"Oakley1997\", \"data\". For details see vignette: https://wadpac.github.io/GGIR/articles/chapter8_SleepFundamentalsSibs.html

Sadeh_axis

Character (default = \"Y\"). To indicate which axis to use for the Sadeh1994 algorithm, and other algortihms that relied on count-based Actigraphy such as Galland2012.

sleeplogsep

Character (default = NULL). This argument is deprecated.

nap_model

Character (default = NULL). To specify classification model. Currently the only option is \"hip3yr\", which corresponds to a model trained with hip data in 3-3.5 olds trained with parent diary data. This functionality is currently superseded by nap detection which is triggered by possible_nap_window and possible_nap_dur. Leave nap_model as NULL when using the new functionality. More documentation to follow in 2025 when development work has completed.

longitudinal_axis

Integer (default = NULL). To indicate which axis is the longitudinal axis. If not provided, the function will estimate longitudinal axis as the axis with the highest 24 hour lagged autocorrelation. Only used when sensor.location = \"hip\" or HASPT.algo = \"HorAngle\".

anglethreshold

Numeric (default = 5). Angle threshold (degrees) for sustained inactivity periods detection. The algorithm will look for periods of time (timethreshold) in which the angle variability is lower than anglethreshold. This can be specified as multiple thresholds, each of which will be implemented, e.g., anglethreshold = c(5,10).

timethreshold

Numeric (default = 5). Time threshold (minutes) for sustained inactivity periods detection. The algorithm will look for periods of time (timethreshold) in which the angle variability is lower than anglethreshold. This can be specified as multiple thresholds, each of which will be implemented, e.g., timethreshold = c(5,10).

possible_nap_window

Numeric (default = NULL). Numeric vector of length two with range in clock hours during which naps are assumed to take place, e.g., possible_nap_window = c(9, 18). The nap classification is only applied if both possible_nap_window and possible_nap_dur are specified. More documentation to follow in 2025 when development work has completed.

possible_nap_dur

Numeric (default = NULL). Numeric vector of length two with range in duration (minutes) of a nap, e.g., possible_nap_dur = c(15, 240). The nap classification is only applied if both possible_nap_window and possible_nap_dur are both specified. More documentation to follow in 2025 when development work has completed.

sleepefficiency.metric

Numeric (default = 1). If 1 (default), sleep efficiency is calculated as detected sleep time during the SPT window divided by log-derived time in bed. If 2, sleep efficiency is calculated as detected sleep time during the SPT window divided by detected duration in sleep period time plus sleep latency (where sleep latency refers to the difference between time in bed and sleep onset). sleepefficiency.metric is only considered when parameter sleepwindowType = \"TimeInBed\"

possible_nap_edge_acc

Numeric (default = Inf). Maximum acceleration before or after the SIB for the nap to be considered. By default this will allow all possible naps.

possible_nap_gap

Numeric (default = 0). Time gap expressed in seconds that is allowed between the sustained inactivity bouts that form the naps.

sib_must_fully_overlap_with_TimeInBed

Boolean (default = c(TRUE, TRUE)). To indicate whether sib must fully overlap with TimeInBed to be considered sleep for the start and end of time in bed, respectively. Only considered when parameter sleepwindowType = \"TimeInBed\". Note that negative sleep latency, if any, will be reported in the night summary report (part4_nightsummary_sleep csv files) but these negative sleep latency and corresponding sleep efficiency values when calculating the person summary aggregate as stored in the person level report (part4_summary_sleep csv files).

oakley_threshold

Numeric (default = 20) Threshold as used by the Oakley algorithm. Original documentation suggestion to choose between 20, 40 or 80, while in GGIR this can be any absolute number.

consider_marker_button

Boolean (default = FALSE) Whether to consider the marker button as guider. Currently only functional for Actiwatch-type count-accelerometers such as Philips Health Band and MotionWatch 8. For details see: https://wadpac.github.io/GGIR/articles/chapter9_SleepFundamentalsGuiders.html

impute_marker_button

Boolean (default = FALSE) Whether to impute marker buttons on other days of the recording in the context of using it as guider with consider_marker_button. For details see https://wadpac.github.io/GGIR/articles/chapter9_SleepFundamentalsGuiders.html

nap_markerbutton_method

Numeric (default = 0) Integer to indicate whether and how to use marker button for nap detection: 0 = do not use marker button for nap detection (default); 1 = if marker button is available use it for nap detection, if not rely on accelerometer. 2 = nearby marker button is condition for nap detection but rely on accelerometer to define exact nap timing, and; 3 = nearby marker button is condition for nap detection and used instead of accelerometer classification.

nap_markerbutton_max_distance

Numeric (default = 30) When using nap_markerbutton_method with a value other than 0 nap_markerbutton_max_distance sets the maximum distance in minutes between the nearest marker button and the edge of a sustained inactivity bout. If the marker button lies inside the sustained inactivity bout but beyond the midpoint, no maximum distance is applied. For example, if a sustained activity bout lasts from 11:00:00 to 13:00:00 then its midpoint will be 12:00:00 and with the default nap_markerbutton_max_distance any marker button between 10:30:00 and 12:00:00 will be considered valid for the start of the nap and any marker button between 12:00:00 and 13:30:00 will be considered valid for the end of the nap.

SRI1_smoothing_wsize_hrs

Numeric (default = NULL) As used for Sleep Regularity Calculation in g.part3. If SRI1_smoothing_wsize_hrs and SRI1_smoothing_frac are both specified, this is the windowsize for smoothing of detected sustained inactivity bouts before calculating SRI1. For example, if set to 1 and 0.8, we apply a rolling 1 hour window where each window with 80% or more sleep is classificed as sleep.

SRI1_smoothing_frac

Numeric (default = NULL) As used for Sleep Regularity Calculation in g.part3. If SRI1_smoothing_wsize_hrs and SRI1_smoothing_frac are both specified, this is the fraction used to smooth detected sustained inactivity bouts before calculating SRI1. For example, if set to 1 and 0.8, we apply a rolling 1 hour window where each window with 80% or more sleep is classificed as sleep.

params_247

A list of parameters releated to description of 24/7 behaviours that do not fall under conventional physical activity or sleep outcomes, these parameters are used in GGIR g.part2 and GGIR g.part5:

qwindow

Numeric or character (default = c(0, 24)). To specify windows over which all variables are calculated, e.g., acceleration distribution, number of valid hours, LXMX analysis, MVPA. If numeric, qwindow should have length two, e.g., qwindow = c(0, 24), all variables will only be calculated over the full 24 hours in a day. If qwindow = c(8, 24) variables will be calculated over the window 0-8, 8-24 and 0-24. All days in the recording will be segmented based on these values. If you want to use a day specific segmentation in each day then you can set qwindow to be the full path to activity diary file (character). Expected format of the activity diary is: First column headers followed by one row per recording, first column is recording ID, which needs to match with the ID GGIR extracts from the accelerometer file. Followed by date column in format \"23-04-2017\", where date format is specified by parameter qwindow_dateformat (below). Use the character combination date, Date or DATE in the column name. This is followed by one or multiple columns with start times for the activity types in that day format in hours:minutes:seconds. The header of the column will be used as label for each activity type. Insert a new date column before continuing with activity types for next day. Leave missing values empty. If an activity log is used then individuals who do not appear in the activity log will still be processed with value qwindow = c(0, 24). Dates with no activity log data can be skipped, no need to have a column with the date followed by a column with the next date. If times in the activity diary are not multiple of the short window size (epoch length), the next epoch is considered (e.g., with epoch of 5 seconds, 8:00:02 will be redefined as 8:00:05 in the activity log). When using the qwindow functionality in combination with GGIR part 5 then make sure to check that parameters segmentWEARcrit.part5 and segmentDAYSPTcrit.part5 are specified to your research needs. When using an activity diary be aware that any column name including the words \"impute\" or \"uncertain\" will be ignored. This means you can, for you own convenience, add columns to log which timestamps have been manually imputed or are considered uncertain.

qwindow_dateformat

Character (default = \"%d-%m-%Y\"). To specify the date format used in the activity log as used by strptime. For guidance on how to specify time formats in R see: https://wadpac.github.io/GGIR/articles/DateTimeFormatsInR.html

M5L5res

Numeric (default = 10). Resolution of L5 and M5 analysis in minutes.

winhr

Numeric (default = 5). Vector of window size(s) (unit: hours) of LX and MX analysis, where look for least and most active consecutive number of X hours.

qlevels

Numeric (default = NULL). Vector of percentiles for which value needs to be extracted. These need to be expressed as a fraction of 1, e.g., c(0.1, 0.5, 0.75). There is no limit to the number of percentiles. If left empty then percentiles will not be extracted. Distribution will be derived from short epoch metric data. Parameter qlevels can for example be used for the MX-metrics (e.g. Rowlands et al) as discussed in https://wadpac.github.io/GGIR/articles/chapter7_DescribingDataWithoutKnowingSleep.html#sets-of-quantiles-mx-metrics-by-rowlands-et-al-

ilevels

Numeric (default = NULL). Levels for acceleration value frequency distribution in mg, e.g., ilevels = c(0,100,200). There is no limit to the number of levels. If left empty then the intensity levels will not be extracted. Distribution will be derived from short epoch metric data.

iglevels

Numeric (default = NULL). Levels for acceleration value frequency distribution in mg used for intensity gradient calculation (according to the method by Rowlands 2018). By default this is parameter is empty and the intensity gradient calculation is not done. The user can either provide a single value (any) to make the intensity gradient use the bins iglevels = c(seq(0, 4000, by = 25), 8000) or the user could specify their own distribution. There is no constriction to the number of levels.

IVIS_windowsize_minutes

This argument has been deprecated.

IVIS_epochsize_seconds

Numeric (default = NULL). This parameter has been deprecated.

IVIS.activity.metric

This argument has been deprecated.

IVIS_acc_threshold

This argument has been deprecated.

qM5L5

Numeric (default = NULL). Percentiles (quantiles) to be calculated over L5 and M5 window.

MX.ig.min.dur

Numeric (default = 10). Minimum MX duration needed in order for intensity gradient to be calculated.

LUXthresholds

Numeric (default = c(0, 100, 500, 1000, 3000, 5000, 10000)). Vector with numeric sequence corresponding to the thresholds used to calculate time spent in LUX ranges.

LUX_cal_constant

Numeric (default = NULL). If both LUX_cal_constant and LUX_cal_exponent are provided LUX values are converted based on formula y = constant * exp(x * exponent)

LUX_cal_exponent

Numeric (default = NULL). If both LUX_cal_constant and LUX_cal_exponent are provided LUX LUX values are converted based on formula y = constant * exp(x * exponent)

LUX_day_segments

Numeric (default = NULL). Vector with hours at which the day should be segmented for the LUX analysis.

L5M5window

Has been deprecated after version 1.5-24. This parameter used to define the start and end time, in 24 hour clock hours, over which L5M5 needs to be calculated. Now this is done with parameter qwindow.

cosinor

Boolean (default = FALSE). Whether to apply the cosinor analysis from the ActCR package in part 2. In part 6 cosinor analysis is applied by default and cannot be turned off.

part6CR

Boolean (default = FALSE) to indicate whether circadian rhythm analysis should be run by part 6, this includes: cosinor analysis, extended cosinor analysis, IS, IV, and phi. Optionally this can be expanded with detrended fluctutation analysis which is controlled by parameter 'part6DFA'.

part6HCA

Boolean (default = FALSE) to indicate whether Household Co Analysis should be run by part 6.

part6Window

Character vector with length two (default = c(\"start\", \"end\")) to indicate the start and the end of the time series to be used for circadian rhythm analysis in part 6. In other words, this parameters is not used for Household co-analysis. Alternative values are: \"Wx\", \"Ox\", \"Hx\", where \"x\" is a number to indicat the xth wakeup, onset or hour of the recording. Negative values for \"x\" are also possible and will count relative to the end of the recording. For example, c(\"W1\", \"W-1\") goes from the first till the last wakeup, c(\"H5\", \"H-5\") ignores the first and last 5 hours, and c(\"O2\", \"W10\") goes from the second onset till the 10th wakeup time.

part6DFA

Boolean (default = FALSE) to indicate whether to perform Detrended Fluctuation Analysis. Turned off by default because it can be time consuming.

clevels

Not fully operational yet, to be actived in 2025. Numeric vector (default = c(30, 150)) with length 2 to indicate cadence ranges used when summarising step counts, if available. When set to NULL, step counts will not be summarised in part 5 output.

part6DFA

Boolean (default = FALSE) to indicate whether to perform Detrended Fluctuation Analysis. Turned off by default because it can be time consuming.

SRI2_WASOmin

Numeric (default = 30) Minimum WASO duration in minutes as used for Sleep Regularity Calculation in g.part6.

params_output

A list of parameters used to specify whether and how GGIR stores its output at various stages of the process.

storefolderstructure

Boolean (default = FALSE). Store folder structure of the accelerometer data.

do.part2.pdf

Boolean (default = TRUE). In g.part2: Whether to generate a pdf for g.part2.

do.part3.pdf

Boolean (default = FALSE). In g.part3: Whether to generate a pdf for g.part3.

timewindow

Character (default = c(\"MM\", \"WW\")). In g.part5: Timewindow over which summary statistics are derived. Value can be \"MM\" (midnight to midnight), \"WW\" (waking time to waking time), \"OO\" (sleep onset to sleep onset), or any combination of them.

save_ms5rawlevels

Boolean (default = TRUE). In g.part5: Whether to save the time series classification (levels) as csv or RData files (as defined by save_ms5raw_format). Note that time stamps will be stored in the column timenum in UTC format (i.e., seconds from 1970-01-01). To convert timenum to time stamp format, you need to specify your desired time zone, e.g., as.POSIXct(mdat$timenum, tz = \"Europe/London\"). If you are not using GGIR part 6, are not interested in the visualreport generation, and not interested in time series then you may want to consider setting this parameter to FALSE.

save_ms5raw_format

Character (default = \"RData\"). In g.part5: To specify how data should be stored: \"csv\", \"RData\", or both via c(\"csv\", \"RData\"). Only used if save_ms5rawlevels = TRUE.

save_ms5raw_without_invalid

Boolean (default = TRUE). In g.part5: To indicate whether to remove invalid days from the time series output files. Only used if save_ms5rawlevels = TRUE.

epochvalues2csv

Boolean (default = FALSE). In g.part2: If TRUE then epoch values are exported to a csv file. Here, non-wear time is imputed where possible.

do.sibreport

Boolean (default = TRUE). In g.part4: To indicate whether to generate report for the sustained inactivity bouts (SIB). If set to TRUE and when an advanced sleep diary is available in part 4 then part 5 will use this to generate summary statistics on the overlap between self-reported nonwear and napping with SIB. Here, SIB can be filter based on parameter possible_nap_edge_acc and the first value of possible_nap_dur

do.visual

Boolean (default = TRUE). In g.part4: If TRUE, the function will generate a pdf with a visual representation of the overlap between the sleeplog entries and the accelerometer detections. This can be used to visually verify that the sleeplog entries do not come with obvious mistakes.

outliers.only

Boolean (default = FALSE). In g.part4: Only used if do.visual = TRUE. If FALSE, all available nights are included in the visual representation of the data and sleeplog. If TRUE, then only nights with a difference in onset or waking time larger than the variable of parameter criterror will be included.

criterror

Numeric (default = 3). In g.part4: Only used if do.visual = TRUE and outliers.only = TRUE. criterror specifies the number of minimum number of hours difference between sleep log and accelerometer estimate for the night to be included in the visualisation.

visualreport

Boolean (default = TRUE). If TRUE, store two visualreports in outputfolder 'results/file summary reports' with names starting with \"old_report_...\" and \"report...\". The report \"old_report_...\" has been in GGIR for years and is based on combined output from GGIR part 2 and 4. It was initially only a quick development attempt to have something to show to study participants back in 2015. This report is not designed for data quality checking purposes as it makes no attempt to exactly visualise the classifications made in GGIR part 5. Given the number of inaccuracies, this report will eventually be deprecated from GGIR. To turn off the old report use old_visualreport = FALSE. \"report_...\", is a new report as of GGIR 3.1-8 and is specifically aimed at supporting data quality checks as it shows the time series data as generated and used in GGIR part 5.

.

viewingwindow

Numeric (default = 1). Centre the day as displayed around noon (viewingwindow = 1) or around midnight (viewingwindow = 2) in the \"Report_\" visual report generated with visualreport = TRUE.

week_weekend_aggregate.part5

Boolean (default = FALSE). In g.part5: To indicate whether week and weekend-days aggregates should be stored. This is turned off by default as it generates a large number of extra columns in the output report.

dofirstpage

Boolean (default = TRUE). To indicate whether a first page with histograms summarizing the whole measurement should be added in the file summary reports named \"old_report_\" generated with visualreport = TRUE.

sep_reports

Character (default = \",\"). Value used as sep parameter in fwrite for writing csv reports.

dec_reports

Character (default = \".\"). Value used as dec parameter in fwrite for writing csv reports.

sep_config

Character (default = \",\"). Value used as sep parameter in fwrite for writing csv config file.

dec_config

Character (default = \".\"). Value used as dec parameter in fwrite for writing csv config file.

visualreport_without_invalid

Boolean (default = TRUE). If TRUE, then reports generated with visualreport = TRUE named \"old_report_\" only show the windows with sufficiently valid data according to includedaycrit when viewingwindow = 1 or includenightcrit when viewingwindow = 2

require_complete_lastnight_part5

Boolean (default = FALSE). When set to TRUE: The last WW window is excluded if the recording ends between midnight and 3pm, and starts on a date that is on or one day before the recording end date; The last OO and MM window are excluded if recording ends between midnight and 9am, and starts on a date that is on or one day before the recording end date. This to avoid risk that recording end biases the sleep estimates for the last night.

old_visualreport

Boolean (default = TRUE). If TRUE, then generate old visual report in addition to new visualreport. The old visualreport will eventually be deprecated

visualreport_hrsPerRow

Numeric (default = 36). Width of the plots in the new visualreport (named \"report_...\") expressed in hours. Expected to be in the range 24-48. If more than 24 then the extra time overlaps with the beginning of the next plot.

visualreport_focus

Character (default = \"day\") Whether new visual report (names start with \"report...\") focuss on day or night. If set ot \"night\" the focus will be on the night.

visualreport_validcrit

Numeric (default = 0). Value between 0 and 1 representing the fraction of data in a plot that is expected to be valid. If this criteria is not met the row is skipped. Only used in new visual report (names start with \"report...\").

method_research_vars

Character (default = NULL). Vector with names of methodological variable categories to store in the csv output files. Currently on \"nap\" is available which affects the part5 output. The variables are intended for methodological research only and are by default turned off.

Value

The function provides no values, it only ensures that other functions are called and that their output is stored. Further, a configuration file is stored containing all the argument values used to facilitate reproducibility.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

## Not run: 
  mode = c(1,2,3,4,5)
  datadir = \"C:/myfolder/mydata\"
  outputdir = \"C:/myresults\"
  studyname =\"test\"
  f0 = 1
  f1 = 2
  GGIR(#-------------------------------
       # General parameters
       #-------------------------------
       mode = mode,
       datadir = datadir,
       outputdir = outputdir,
       studyname = studyname,
       f0 = f0,
       f1 = f1,
       overwrite = FALSE,
       do.imp = TRUE,
       idloc = 1,
       print.filename = FALSE,
       storefolderstructure = FALSE,
       #-------------------------------
       # Part 1 parameters:
       #-------------------------------
       windowsizes = c(5,900,3600),
       do.cal = TRUE,
       do.enmo = TRUE,
       do.anglez = TRUE,
       chunksize = 1,
       printsummary = TRUE,
       #-------------------------------
       # Part 2 parameters:
       #-------------------------------
       data_masking_strategy = 1,
       ndayswindow = 7,
       hrs.del.start = 1,
       hrs.del.end = 1,
       maxdur = 9,
       includedaycrit = 16,
       L5M5window = c(0,24),
       M5L5res = 10,
       winhr = c(5,10),
       qlevels = c(c(1380/1440),c(1410/1440)),
       qwindow = c(0,24),
       ilevels = c(seq(0,400,by=50),8000),
       mvpathreshold = c(100,120),
       #-------------------------------
       # Part 3 parameters:
       #-------------------------------
       timethreshold = c(5,10),
       anglethreshold = 5,
       ignorenonwear = TRUE,
       #-------------------------------
       # Part 4 parameters:
       #-------------------------------
       excludefirstlast = FALSE,
       includenightcrit = 16,
       def.noc.sleep = 1,
       loglocation = \"D:/sleeplog.csv\",
       outliers.only = FALSE,
       criterror = 4,
       relyonguider = FALSE,
       colid = 1,
       coln1 = 2,
       do.visual = TRUE,
       #-------------------------------
       # Part 5 parameters:
       #-------------------------------
       # Key functions: Merging physical activity with sleep analyses
       threshold.lig = c(30,40,50),
       threshold.mod = c(100,120),
       threshold.vig = c(400,500),
       excludefirstlast = FALSE,
       boutcriter = 0.8,
       boutcriter.in = 0.9,
       boutcriter.lig = 0.8,
       boutcriter.mvpa = 0.8,
       boutdur.in = c(10,20,30),
       boutdur.lig = c(1,5,10),
       boutdur.mvpa = c(1,5,10),
       timewindow = c(\"WW\"),
       #-----------------------------------
       # Report generation
       #-------------------------------
       do.report = c(2,4,5))

       # For externally derived Actiwatch data in .AWD format:
       GGIR(datadir = \"/media/actiwatch_awd\", # folder with epoch level .AWD file
          outputdir = \"/media/myoutput\",
          dataFormat = \"actiwatch_awd\",
          extEpochData_timeformat = \"%m/%d/%Y %H:%M:%S\",
          mode = 1:5,
          do.report = c(2, 4, 5),
          windowsizes = c(60, 900, 3600), # 60 is the expected epoch length
          visualreport = FALSE,
          outliers.only = FALSE,
          overwrite = TRUE,
          HASIB.algo = \"Sadeh1994\",
          def.noc.sleep = c()) # <= because we cannot use HDCZA for ZCY

       # For externally derived Actiwatch data in .CSV format:
       GGIR(datadir = \"/media/actiwatch_csv\", # folder with epoch level .AWD file
          outputdir = \"/media/myoutput\",
          dataFormat = \"actiwatch_csv\",
          extEpochData_timeformat = \"%m/%d/%Y %H:%M:%S\",
          mode = 1:5,
          do.report = c(2, 4, 5),
          windowsizes = c(15, 900, 3600), # 15 is the expected epoch length
          visualreport = FALSE,
          outliers.only = FALSE,
          HASIB.algo = \"Sadeh1994\",
          def.noc.sleep = c()) # <= because we cannot use HDCZA for ZCY

       # For externally derived UK Biobank data in .CSV format:
       GGIR(datadir = \"/media/ukbiobank\",
           outputdir = \"/media/myoutput\",
           dataFormat = \"ukbiobank_csv\",
           extEpochData_timeformat = \"%m/%d/%Y %H:%M:%S\",
           mode = c(1:2),
           do.report = c(2),
           windowsizes = c(5, 900, 3600), # We know that data was stored in 5 second epoch
           desiredtz = \"Europe/London\", # We know that data was collected in the UK
           visualreport = FALSE,
           overwrite = TRUE)
        
       # For externally derived ActiGraph count data in .CSV format assuming
       # a study protocol where sensor was not worn during the night:
       GGIR(datadir = \"/examplefiles\",
           outputdir = \"\",
           dataFormat = \"actigraph_csv\",
           mode = 1:5,
           do.report = c(2, 4, 5),
           windowsizes = c(5, 900, 3600),
           threshold.in = round(100 * (5/60), digits = 2),
           threshold.mod = round(2500 * (5/60), digits = 2),
           threshold.vig = round(10000 * (5/60), digits = 2),
           extEpochData_timeformat = \"%m/%d/%Y %H:%M:%S\",
           do.neishabouricounts = TRUE,
           acc.metric = \"NeishabouriCount_x\",
           HASPT.algo = \"NotWorn\",
           HASIB.algo = \"NotWorn\",
           do.visual = TRUE,
           includedaycrit = 10,
           includenightcrit = 10,
           visualreport = FALSE,
           outliers.only = FALSE,
           save_ms5rawlevels = TRUE,
           ignorenonwear = FALSE,
           HASPT.ignore.invalid = FALSE,
           save_ms5raw_without_invalid = FALSE)
           
           
       # For externally derived Sensear data in .xls format:  
        GGIR(datadir = \"C:/yoursenseweardatafolder\",
            outputdir = \"D:/youroutputfolder\",
            mode = 1:5,
            windowsizes = c(60, 900, 3600),
            threshold.in = 1.5,
            threshold.mod = 3,
            threshold.vig = 6,
            dataFormat = \"sensewear_xls\",
            extEpochData_timeformat = \"%d-%b-%Y %H:%M:%S\",
            HASPT.algo = \"NotWorn\",
            desiredtz = \"America/New_York\",
            overwrite = TRUE,
            do.report = c(2, 4, 5),
            visualreport = FALSE)
           
  
## End(Not run)

Heuristic algorithms for sustiained inactivty bouts detection

Description

Apply heuristic algorithms for sustiained inactivty bouts detection. Function not intended for direct use by package user

Usage

  HASIB(HASIB.algo = "vanHees2015", timethreshold = c(), anglethreshold = c(), 
                 time = c(), anglez = c(), ws3 = c(), zeroCrossingCount = c(),
                 NeishabouriCount = c(), activity = NULL,
                 oakley_threshold = NULL)

Arguments

HASIB.algo

Character to indicator which sib algorithm should be used. Default value: "vanHees2015". Other options: "Sadeh1994", "Galland2012", "ColeKripke1992"

anglethreshold

See g.sib.det

timethreshold

See g.sib.det

time

Vector with time per short epoch

anglez

Vector with z-angle per short epoch

ws3

See g.getmeta

zeroCrossingCount

Vector with zero crossing counts per epoch as required for count-based algorithms

NeishabouriCount

Vector with Neishabouri counts per epoch to be used by the count-based algorithms

activity

Magnitude of acceleration, only used when HASIB.algo is set to NotWorn or Oakley1997. Acceleration metric used is specified by argument acc.metric elsewhere in GGIR.

oakley_threshold

See GGIR

Value

Vector with binary indicator of sustained inactivity bout, 1 is yes, 0 is no.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Heuristic Algorithms estimating SPT window.

Description

As used in function g.sib.det. Function is not intended for direct use by GGIR user.

Usage

HASPT(angle, sptblocksize = 30, spt_max_gap = 60, ws3 = 5, 
      HASPT.algo="HDCZA", HDCZA_threshold = c(), invalid, 
      HASPT.ignore.invalid = FALSE, activity = NULL,
      marker = NULL, sibs = NULL, try_marker_button = FALSE)

Arguments

angle

Vector of epoch level estimates of angle

sptblocksize

Number to indicate minimum SPT block size (minutes)

spt_max_gap

Number to indicate maximum gap (minutes) in SPT window blocks.

ws3

Number representing epoch length in seconds

HASPT.algo

See GGIR

HDCZA_threshold

See GGIR

invalid

Integer vector with per epoch an indicator of valid(=0) or invalid(=1) epoch.

HASPT.ignore.invalid

Boolean to indicate whether invalid time segments should be ignored

activity

Numeric vector with magnitude of acceleration per epoch, only used when HASPT.algo is set to NotWorn. Acceleration metric used is specified by argument acc.metric elsewhere in GGIR.

marker

Optional, numeric vector with for each epoch an indication of whether the marker button was pressed (1) or not (0). Only used for Actiwatch-like devices such as MotionWare.

sibs

Numeric vector of classified sibs with HASIB, experimental not used at the moment.

try_marker_button

See GGIR

Value

List with start and end times of the SPT window and the threshold as used.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


MX LX analysis

Description

Identifies the most and least active X hours

Usage

   MXLX(Y = NULL, X = 5, epochSize = 1, tseg = c(0, 24), resolutionMin = 10)

Arguments

Y

Vector with numeric time series

X

Single numeric value of X in hours

epochSize

Numeric epoch size in seconds of Y

tseg

Numeric vector of length two reflecting the time windownof Y in real clock hours. For example, if Y represent noon-midnight then set tseg to c(12, 24).

resolutionMin

Numeric value to indicate the resolution in minutes of the MX and LX search

Value

A data.frame with the:

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Convert POSIX to iso8601 timestamp

Description

To avoid ambiguities when sharing and comparing timestamps. All timestamps are expressed in iso8601 format: https://en.wikipedia.org/wiki/ISO_8601

Usage

POSIXtime2iso8601(x,tz)	

Arguments

x

Vector of timestamps in POSIX format

tz

Timezone of data collection, e.g. "Europe/London". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for full list

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

## Not run: 
x ="2017-05-07 13:15:17 CEST"
tz = "Europe/Amsterdam"
x_converted = POSIXtime2iso8601(x,tz)

## End(Not run)

Estimated self-similarity parameter

Description

This function estimates the self-similarity parameter (SSP), also known as scaling exponent or alpha.

Usage

  SSP(data,scale = 2^(1/8),box_size = 4,m=1)

Arguments

data

Univariate time series (must be a vector or data frame)

scale

Specifies the ratio between successive box sizes (by default scale = 2^(1/8))

box_size

Vector of box sizes (must be used in conjunction with scale = "F")

m

An integer of the polynomial order for the detrending (by default m=1)

Details

The DFA fluctuation can be computed in a geometric scale or for different choices of boxes sizes.

Value

Estimated alpha is a real number between zero and two.

Note

It is not possible estimating alpha for multiple time series at once.

Author(s)

Ian Meneghel Danilevicz <ian.meneghel-danilevicz@inserm.fr> Victor Barreto Mesquita <victormesquita40@hotmail.com>

References

C.-K. Peng, S.V. Buldyrev, S. Havlin, M. Simons, H.E. Stanley, A.L. Goldberger Phys. Rev. E, 49 (1994), p. 1685 Mesquita, Victor & Filho, Florencio & Rodrigues, Paulo. (2020). Detection of crossover points in detrended fluctuation analysis: An application to EEG signals of patients with epilepsy. Bioinformatics. 10.1093/bioinformatics/btaa955.

Examples

  # Estimate self-similarity of a very known time series available on R base: the sunspot.year.
  # Then the spend time with each method is compared.
  ## Not run: 
    ssp = SSP(sunspot.year)
  
## End(Not run)

Extract Definition from Shell Documentation

Description

Function extracts the documentation for a given GGIR argument as provided in the GGIR documentation. Function not designed for direct use by package user.

Usage

  ShellDoc2Vignette(argument = "mode")

Arguments

argument

Character (default = "mode"). Name of the argument to extract the definition.

Value

Character object with the definition of the argument.

Author(s)

Jairo Hidalgo Migueles <jairo.hidalgo.migueles@gmail.com>


Add split names to output object in g.part4 and g.part5

Description

Internal function to add the recording split names to output the reports for GGIR part 4 and 5.

Usage

   addSplitNames(x)

Arguments

x

Output data.frame as generated inside g.part4 and g.part5.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Aggregates event data as produced by external function

Description

Aggregates event data as produced by external function

Usage

   aggregateEvent(metric_name, epochsize, daysummary, ds_names,
                          fi, di, vari, segmentInfo, myfun = NULL,
                          params_247)

Arguments

metric_name

Character with name of metric

epochsize

Numeric epochsize in seconds of the timeseries

daysummary

Matrix with prelimenary day summary

ds_names

Daysummary column names

fi

Column index of daysummary

di

Row index of daysummary representing the recording day

vari

Time series derived from metashort

segmentInfo

List passed on from g.analyse.perday with time series indices of segment to analyse segment name and segment number.

myfun

See GGIR

params_247

See GGIR

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Append GGIR milestone data from neighbouring or overlapping recordings

Description

Append GGIR part 1 milestone data format from neighbouring or overlapping recording. When recordings overlap we use data from newest recordings. When time gap is larger than 2 days the recordings are not appended. Not intended for direct use by the user.

Usage

   appendRecords(metadatadir, desiredtz = "", idloc = 1, maxRecordingInterval = NULL)

Arguments

metadatadir

See g.part2

desiredtz

See GGIR

idloc

See GGIR

maxRecordingInterval

See GGIR

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Apply external function to acceleration data.

Description

Applies external function to the raw acceleration data within GGIR. This makes it easier for new algorithms developed to be pilotted on accelerometer data while taking advantage of the existing comprehensive GGIR data management and analysis infrastructure. This function is not for direct interaction by user, please supply object myfun to GGIR or g.part1. Object myfun is a list as detailed below.

Usage

  applyExtFunction(data, myfun, sf, ws3, interpolationType=1)
  

Arguments

data

Data data.frame as present internally in g.getmeta. It has at least four columns of which the first is the timestamp followed by the x, y, and z acceleration.

myfun

See details, in short: myfun is a list object that holds the external function to be applied to the data and various parameters to aid in the process.

sf

Sample frequency (Hertz) of the data object

ws3

Short epoch size (first value of windowsizes in g.getmeta).

interpolationType

Integer to indicate type of interpolation to be used when resampling time series (mainly relevant for Axivity sensors), 1=linear, 2=nearest neighbour.

Details

See package vignette for detailed tutorial with examples on how to use the function embedding: https://cran.r-project.org/web/package=GGIR/vignettes/applyExtFunction.pdf Function applyExtFunction is typically not used by the GGIR user directly.

Value

The output of the external algorithm aggregated or repeated to fit the short epoch length of GGIR. Therefore, the short epoch length of GGIR should be a multitude of the resolution of the external function output, or visa versa.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Apply Cosinor Analyses to time series

Description

Wrapper function around cosinor_IS_IV_Analyses that first prepares the time series before applying the cosinorAnlayses

Usage

  apply_cosinor_IS_IV_Analyses(ts, qcheck, midnightsi, epochsizes, threshold = NULL)

Arguments

ts

Data.frame with timestamps and acceleration metric.

qcheck

Vector of equal length as number of rows in ts with value 1 for invalid timestamps, 0 otherwise.

midnightsi

Indices for midnights in the time series

epochsizes

Epoch size for ts and qcheck respectively

threshold

See cosinor_IS_IV_Analyses

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Checks for existence of folders to process

Description

Checks whether milestone folders exist, create them if needed, and check whether folders are not empty. Only done for part 1 to 5 and not part 6, which is different and handled inside g.part6.

Usage

  checkMilestoneFolders(metadatadir, partNumber)

Arguments

metadatadir

Character, path to root of outputfolder.

partNumber

Numeric, number from the set 2, 3, 4 or 5.

Value

No value is produced

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Function to revise format of user-provided logs

Description

Function to revise the format for missing values and dates in user-provided

Usage

  check_log(log, dateformat, colid = 1, datecols = c(), 
            logPath, logtype)	

Arguments

log

Data frame with the log as read by data.table::fread.

dateformat

Character specifying the expected date format used in the log.

colid

Numeric with the column containing the file ID.

datecols

Numeric with the column/s containing the dates.

logPath

Character containing the full path to the activity log that is being checked.

logtype

Character which accepts "activity log" or "study dates log" at the moment. Only used for warning messages.

Value

Data.frame containing the revised log.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Jairo H Migueles <jairo@jhmigueles.com>


Checks myfun object before it is passed to applyExtfunction

Description

Checks that object myfun is a list and check the elements of the list for: that element names are as expected, that value of each element is of the expected type and length.

Usage

  check_myfun(myfun, windowsizes)
  

Arguments

myfun

See applyExtFunction

windowsizes

See g.getmeta).

Value

0 if all checkes passed, 1 if one or more checks did not pass. Error message are printed to the console with feedback on which checks did not pass.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Check default parameters

Description

Checks parameter objects for class and logical combinations. Called from extract_params. Not intended for direct use by GGIR users.

Usage

  check_params(params_sleep = c(), params_metrics = c(),
                        params_rawdata = c(), params_247 = c(),
                        params_phyact = c(), params_cleaning = c(),
                         params_output = c(), params_general = c())

Arguments

params_sleep

List with sleep parameters

params_metrics

List with parameters related to metrics

params_rawdata

List with parameters related to raw data reading and processing

params_247

List with parameters related to 24/7 behavioural analysis, which includes anything that does not fit with physical activity or sleep research

params_phyact

List with parameters related to physical activity analysis

params_cleaning

List with parameters related to cleaning the time series, including masking and imputation

params_output

List with parameters related to how GGIR stores its output

params_general

List with parameters related to general topics

Value

Lists of updated parameter objects

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


convert external Epoch data to GGIR part 1 milestone data format

Description

convert externally created Epoch data to GGIR part 1 milestone data format. Function not intended for direct use by user. The aim is to allow for using GGIR on top of extrnally derived epoch data. See argument dataFormat in the GGIR for details on how to use this functionality.

Usage

   convertEpochData(datadir = c(), metadatadir = c(),
                    params_general = c(), f0 = c(), f1 = c(), verbose = TRUE)

Arguments

datadir

See GGIR

metadatadir

See GGIR

params_general

Parameters object see GGIR

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

verbose

See GGIR

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Corrects milestone data from g.part1 generated in older GGIR versions

Description

Some older versions of GGIR stored the milestone data in part 1 as factor. This function identifies when that occurs and convert the affected columns to the appropriate class (e.g., numeric).

Usage

  correctOlderMilestoneData(x)

Arguments

x

Data frame with metashort or metalong data as generated in g.part1

Value

Data frame with the class fixed in the appropriate columns (i.e., light and temperature columns)

Examples

  ## Not run: 
    correctOlderMilestoneData(x)
  
## End(Not run)

Apply cosinor anlaysis and extended cosinor analysis

Description

Applies cosinor anlaysis from the ActCR package to the time series, as well as IV, IS and phi estimates.

Usage

  cosinor_IS_IV_Analyses(Xi, epochsize = 60, timeOffsetHours = 0, threshold = NULL)

Arguments

Xi

Vector with time series of movement indicators if the maximum < 8 and mean < 1 then input is assumed to be in g-units and is multiplied by 1000.

epochsize

Numeric epochsize in seconds

timeOffsetHours

Numeric time in hours relative to next midnight

threshold

Numeric value to use as threshold to distinguish inactivity from active behaviour for the IV and IS analysis. GGIR uses parameter threshold.lig to set this threshold.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Creates Config File based on variables in function GGIR environment

Description

Only used inside GGIR. Not intended for direct use by user.

Usage

  createConfigFile(config.parameters = c(), GGIRversion = "")	

Arguments

config.parameters

List with all arguments used in GGIR.

GGIRversion

GGIR version mumber to be incorported in the ConfigFile.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Creates csv data file for testing purposes

Description

Creates file in the Actigraph csv data format with dummy data that can be used for testing. The file includes accelerometer data with bouts of higher acceleration, variations non-movement periods in a range of accelerometer positions to allow for testing the auto-calibration functionality.

Usage

  create_test_acc_csv(sf=3,Nmin=2000,storagelocation=c(),
                      start_time = NULL, starts_at_midnight = FALSE)

Arguments

sf

Sample frequency in Hertz, the default here is low to minimize file size

Nmin

Number of minutes (minimum is 720)

storagelocation

Location where the test file named testfile.csv will be stored If no value is provided then the function uses the current working directory

start_time

Start time of the recording, in the hh:mm:ss format.

starts_at_midnight

Boolean indicating whether the recording should start at midnight. Ignored if start_time is specified.

Value

The function does not produce any output values. Only the file is stored

Examples

  ## Not run: 
    create_test_acc_csv()
  
## End(Not run)

Creates csv sleeplog file for testing purposes

Description

Creates sleeplog file in the format as expected by g.part4 with dummy data (23:00 onset, 07:00 waking time for every night).

Usage

  create_test_sleeplog_csv(Nnights = 7, storagelocation = c(),
                            advanced = FALSE, sep = ",", begin_date = "2016/06/25",
                            type = "sleeplog")

Arguments

Nnights

Number of nights (minimum is 1)

storagelocation

Location where the test file named testfile.csv will be stored If no value is provided then the function uses the current working directory

advanced

Boolean to indicate whether to create an advanced sleeplog that also includes logs of nap times and nonwear

sep

Character to indicate the column separator of the csv file.

begin_date

Character to indicate first date (in format "2016/06/25") to be used in the advanced sleeplog format. Ignored when generated basic sleeplog format.

type

Character to indicate which type of advanced sleeplog to create, either "sleeplog" with "wakeup" and "onset" columns, "bedlog" with "bedstart" and "bedend" columns, or "both" with both.

Value

The function does not produce any output values. Only the file is stored

Examples

  ## Not run: 
    create_test_sleeplog_csv()
  
## End(Not run)

Example output from g.calibrate

Description

data.calibrate is example output from g.calibrate

Usage

data(data.calibrate)

Format

The format is: chr "data.calibrate"

Source

The data was collected on one individual for testing purposes

Examples

data(data.calibrate)

Example output from g.getmeta

Description

data.getmeta is example output from g.getmeta

Usage

data(data.getmeta)

Format

The format is: chr "data.getmeta"

Source

The data was collected on one individual for testing purposes

Examples

data(data.getmeta)

Example output from g.inspectfile

Description

data.inspectfile is example output from g.inspectfile

Usage

data(data.inspectfile)

Format

The format is: chr "data.inspectfile"

Source

The data was collected on one individual for testing purposes

Examples

data(data.inspectfile)

Metalong object as part of part 1 milestone data

Description

data.metalong is example of the metalong data.frame stored g.part1

Usage

data(data.metalong)

Format

The format is: chr "data.metalong"

Source

The data was collected on one individual for testing purposes

Examples

  data(data.metalong)

Time series data.frame stored by part 5

Description

data.ts is example of the data.frame stored g.part5

Usage

data(data.ts)

Format

The format is: chr "data.ts"

Source

The data was collected on one individual for testing purposes and matches the data in object data.metalong

Examples

  data(data.ts)

Generates vector of file names out of datadir input argument

Description

Uses input argument datadir from g.part1 and the output from isfilelist to generate vector of filenames

Usage

  datadir2fnames(datadir,filelist)

Arguments

datadir

See g.part1

filelist

Produced by isfilelist

Value

Character vector of filenames

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
  datadir2fnames(datadir = "C:/mydatafolder",filelist=TRUE)
  
## End(Not run)

Detect non-wear and clipping time in the raw accelerometer data

Description

Detects periods in which the accelerometer has not been worn or the accelerometer signal was stuck very close to the dynamic range limit of the accelerometer.

Usage

detect_nonwear_clipping(data = c(), windowsizes = c(5, 900, 3600), sf = 100,
                        clipthres = 7.5, sdcriter = 0.013, racriter = 0.05,
                        nonwear_approach = "2013",
                        params_rawdata = c())

Arguments

data

Matrix with raw accelerometer data for X, Y, and Z axes.

windowsizes

Numeric vector of length three, with short, long epoch and window size in seconds.

sf

Sample frequency in Hertz.

clipthres

Threschold to detect clipping in _g_ units. Usually 0.5 _g_ below the dynamic range of the accelerometer.

sdcriter

Criteria to define non-wear time, defined as the estimated noise measured in the raw accelerometer data.

racriter

Absolute criteria below which the absolute range of the accelerations should be to define non-wear time.

nonwear_approach

Whether to use the traditional version of the non-wear detection algorithm (nonwear_approach = "2013", default) or the new version (nonwear_approach = "2023"). The 2013 version would use the longsize window (windowsizes[3], one hour as default) to check the conditions for nonwear identification and would flag as nonwear the mediumsize window (windowsizes[2], 15 min as default) in the middle. The 2023 version differs in which it would flag as nonwear the full longsize window. For the 2013 method the longsize window is centered in the centre of the mediumsize window, while in the 2023 method the longsizewindow is aligned with its left edge to the left edge of the mediumsize window.

params_rawdata

See details in GGIR.

Value

List containing the next numeric vectors:

Each number in these vectors represent a long epoch duration (i.e., ws2, 900 seconds by default).

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Jairo Hidalgo Migueles <j.h.migueles@accelting.com>

References

Examples

## Not run: 
    detect_nonwear_clipping(data = data, windowsizes = c(900, 3600), sf = sf,
                            clipthres = clipthres, sdcriter = sdcriter, 
                            racriter = racriter, nonwear_approach = "old")
  
## End(Not run)

Extract ID from file header object

Description

Extract ID from file header object.

Usage

   extractID(hvars, idloc, fname)

Arguments

hvars

Object extracted with g.inspectfile

idloc

See GGIR

fname

File (base)name.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Extract parameters from input and add them to params

Description

Extracts parameters separately provided by input and adds them to the params objects. Not intended for direct use by GGIR users.

Usage

  extract_params(params_sleep = c(), params_metrics = c(),
                 params_rawdata = c(), params_247 = c(),
                 params_phyact = c(), params_cleaning = c(),
                 params_output = c(), params_general = c(), input = c(),
                 configfile_csv = c(), params2check = c("sleep", "metrics",
                 "rawdata", "247", "phyact",
                                           "cleaning", "output", "general"))

Arguments

params_sleep

List with sleep parameters

params_metrics

List with parameters related to metrics

params_rawdata

List with parameters related to raw data reading and processing

params_247

List with parameters related to 24/7 behavioural analysis, which includes anything that does not fit with physical activity or sleep research

params_phyact

List with parameters related to physical activity analysis

params_cleaning

List with parameters related to cleaning the time series, including masking and imputation

params_output

List with parameters related to how GGIR stores its output

params_general

List with parameters related to general topics

input

All objects provided by users

configfile_csv

Csv configuration file

params2check

Character vector to indicate which params objects need to be checked. This allows us to prevent the function from checking params objects that are not used in the context where function extract_params is used.

Value

Lists of updated parameter objects

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Filters short lasting nonwear during the night

Description

Filters short lasting nonwear during the night. Not intended for direct use by GGIR user.

Usage

  filterNonwearNight(r1, metalong, qwindowImp, desiredtz, params_cleaning, ws2)

Arguments

r1

Object r1 as created inside function g.weardec which is a vector of zeros and ones derived from metalong where 1 indicates nonwear and 0 wear.

metalong

Object metalong created in g.part1

qwindowImp

See g.impute

desiredtz

See GGIR

params_cleaning

Parameters object with cleaning paramete, see GGIR.

ws2

Object ws2 which equals the second value of vector parameter windowsizes

Value

r1 object with short lasting nonwear during the night removed

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Calculates IV and IS

Description

To extract interdaily stability and interdaily variability as originally proposed by van Someren.

Usage

  g.IVIS(Xi, epochSize = 60, threshold = NULL)

Arguments

Xi

Vector with acceleration values, e.g. ENMO metric.

epochSize

Epoch size of the values in Xi expressed in seconds.

threshold

Acceleration threshold to distinguish inactive from active

Value

InterdailyStability
IntradailyVariability

Author(s)

Ian Meneghel Danilevicz <ian.meneghel-danilevicz@inserm.fr> Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  Xi = abs(rnorm(n = 10000,mean = 0.2))
  IVISvariables = g.IVIS(Xi=Xi)

Abbreviates daynames to numbers, needed for report generation in g.plot5

Description

Abbreviates daynames Monday becomes MON and Sunday becomes SUN

Usage

  g.abr.day.names(daynames)	

Arguments

daynames

Vector of daynames in character format

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  daynames = c("Monday","Friday")
  daynames_converted = g.abr.day.names(daynames)

Function to analsyse meta-data generated by g.getmeta and g.impute

Description

Analyses the output from other functions within the packages to generate a basic descriptive summary for each accelerometer data file. Analyses include: Average acceleration per day, per measurement, L5M5 analyses (assessment of the five hours with lowest acceleration and with highest acceleration). Further, the traditionally popular variable MVPA is automatically extracted in six variants: without bout criteria in combination with epoch = epoch length as defined in g.getmeta (first value of the input argument windowsizes), 1 minute, and 5 minutes, and for bout durations 1 minute, 5 minutes or 10 minutes in combination with the epoch length as defined in g.getmeta.

Usage

  g.analyse(I, C, M, IMP, params_247 = c(), params_phyact = c(),
                      params_general = c(), params_cleaning = c(),
                      quantiletype = 7, myfun = c(), ID, ...)

Arguments

I

the output from function g.inspectfile

C

the output from function g.calibrate

M

the output from function g.getmeta

IMP

the output from function g.impute

params_247

See GGIR

params_phyact

See GGIR

params_general

See GGIR

params_cleaning

See GGIR

quantiletype

type of quantile function to use (default recommended). For details, see quantile function in STATS package

myfun

External function object to be applied to raw data, see g.getmeta.

ID

ID extracted in g.part2.

...

Any argument used in the previous version of g.analyse, which will now be used to overrule the arguments specified with the parameter objects.

Value

g.analyse generated two data,franeL

summary

summary for the file that was analysed

daysummary

summary per day for the file that was analysed

These data.frames are used by function g.report.part2 to generate csv reports. An exaplantion of all the columns in the data.frame and subsequent csv reports can be found in the package vignette (Output part 2).

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  data(data.getmeta)
  data(data.inspectfile)
  data(data.calibrate)
  ## Not run: 
    #inspect file:
    I = g.inspectfile(datafile)
    
    #autocalibration:
    C = g.calibrate(datafile) 
    
    #get meta-data:
    M = g.getmeta(datafile, desiredtz = "Europe/London", 
    windowsizes = c(5, 900, 3600),
    daylimit = FALSE, offset = c(0, 0, 0), 
    scale = c(1, 1, 1), tempoffset = c(0, 0, 0))
  
## End(Not run)
  #impute meta-data:
  IMP = g.impute(M = data.getmeta, I = data.inspectfile, ID = "01wk0")
  
  #analyse and produce summary:
  A = g.analyse(I = data.inspectfile, C = data.calibrate,
  M = data.getmeta, IMP, ID = "01wk0")

Function supports g.analyse. Not intended for direct use by user.

Description

Generatess average day analyses and fills corresponding output matrix, g.analyse.

Usage

  g.analyse.avday(doquan, averageday, M, IMP, t_TWDI, quantiletype,
                   ws3, doiglevels, firstmidnighti, ws2, midnightsi,
                   params_247 = c(), qcheck = c(), acc.metric = c(),
                   params_phyact = NULL, ...)

Arguments

doquan

Boolean whether quantile analysis should be done

averageday

As produced by g.impute

M

As produced by g.getmeta

IMP

As produced by g.impute

t_TWDI

Same as qwindow as described in g.analyse

quantiletype

see g.analyse

ws3

Epoch size in seconds

doiglevels

Boolean to indicate whether iglevels should be calculated

firstmidnighti

see g.detecmidnight

ws2

see g.weardec

midnightsi

see g.detecmidnight

params_247

See GGIR

qcheck

Vector with indicators of when data is valid (value=0) or invalid (value=1).

acc.metric

Character, see GGIR. Here, it is used to decided which acceleration metric to use for IVIS and cosinor analyses.

params_phyact

See GGIR

...

Any argument used in the previous version of g.analyse.avday, which will now be used to overrule the arguments specified with the parameter objects.

Value

igfullr_names

Intensity gradient variable names

igfullr

Intensity gradient values

QUAN

Quantiles

qlevels_names

Quantile level names

ML5AD
ML5AD_names

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Function supports g.analyse. Not intended for direct use by user.

Description

Generates day specific analyses and fills corresponding output matrix, g.analyse.

Usage

g.analyse.perday(ndays, firstmidnighti, time, nfeatures, 
                midnightsi, metashort, averageday,
                doiglevels, nfulldays,lastmidnight, ws3, ws2, qcheck,
                fname, sensor.location, wdayname, tooshort, includedaycrit,
                doquan, quantiletype, doilevels, domvpa,
                mvpanames, wdaycode, ID,
                deviceSerialNumber, ExtFunColsi, myfun,
                params_247 = c(), params_phyact = c(),
                params_general = c(),
                ...)

Arguments

ndays

Number of days in file

firstmidnighti

see g.detecmidnight

time

timestamp column from metalong converted to character

nfeatures

estimate of number of variables that need to be stored in the output matrix

midnightsi

see g.detecmidnight

metashort

see g.impute

averageday

As produced by g.impute

doiglevels

Boolean to indicate whether iglevels should be calculated

nfulldays

Number of days between the first and last midnight in the recording

lastmidnight

see g.detecmidnight

ws3

Epoch size in seconds

ws2

see g.weardec

qcheck

vector with zeros and ones for each epoch, respenting the quality check derived with g.impute

fname

RData filename produced by g.part1

sensor.location

as produced by g.extractheadervars

wdayname

character with weekdayname

tooshort

0 (file not too short) or 1 (file too short)

includedaycrit

see g.analyse

doquan

Boolean whether quantile analysis should be done

quantiletype

see g.analyse

doilevels

Boolean whether to generate ilevels, see g.analyse

domvpa

Boolean whether to do mvpa analysis

mvpanames

Matrix with 6 columns and 1 row holding the names for the six mvpa variables

wdaycode

Equal to M$wday as produced by g.getmeta

ID

Person Identification number, this can be numeric or character

deviceSerialNumber

As produced by g.extractheadervars

ExtFunColsi

column index of metashort where metric is stored

myfun

External function object to be applied to raw data, see g.getmeta.

params_247

See GGIR

params_phyact

See GGIR

params_general

See GGIR

...

Any argument used in the previous version of g.analyse.perday, which will now be used to overrule the arguments specified with the parameter objects.

Value

daysummary

Summary per day for the file that was analysed

ds_names

Variable names in daysummary

windowsummary

Window summary, only used when selectdayfile is specified

ws_names

Variable names in windowsummary

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Function supports g.analyse. Not intended for direct use by user.

Description

Generates recording specific analyses and fills corresponding output matrix, g.analyse.

Usage

g.analyse.perfile(I, C, metrics_nav,
                 AveAccAve24hr, doquan, doiglevels, tooshort,
                 params_247, params_cleaning, params_general,
                 output_avday, output_perday,
                 dataqual_summary, file_summary)

Arguments

I

output g.inspectfile

C

output g.calibrate

metrics_nav

List with three objects to help navigate the acceleration metrics

AveAccAve24hr

Average acceleration in an average 24 hour cycle

doquan

Boolean whether quantile analysis should be done

doiglevels

Boolean to indicate whether iglevels should be calculated

tooshort

0 (file not too short) or 1 (file too short)

params_247

see GGIR

params_cleaning

see GGIR

params_general

see GGIR

output_avday

Output from g.analyse.avday

output_perday

Output from g.analyse.perday

dataqual_summary

Data.frame with data quality summary indicators produced in g.analyse

Value

filesummary

summary for the file that was analysed

daysummary

Summary per day for the file that was analysed

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Extract metrics from acceleration signals

Description

Function to extract metrics from acceleration signal. Not intended for direct use by user

Usage

  g.applymetrics(data, sf, ws3, metrics2do,
                          n = 4, lb = 0.2, hb = 15,
                          zc.lb = 0.25, zc.hb = 3, 
                          zc.sb = 0.01, zc.order = 2,
                          actilife_LFE = FALSE)

Arguments

data

Three column matrix with x, y, and z acceleration data

n

filter order, see GGIR for details

sf

sample frequency

ws3

Epoch size in seconds

metrics2do

Dataframe with Boolean indicator for all metrics whether they should be extracted or not. For instance, metrics2do$do.bfen = TRUE, indicates that the bfen metric should be extracted

lb

Lower boundery of cut-off frequencies, see GGIR.

hb

Higher boundery of cut-off frequencies, see GGIR.

zc.lb

See GGIR

zc.hb

See GGIR

zc.sb

See GGIR

zc.order

See GGIR

actilife_LFE

See GGIR

Value

Dataframe with metric values in columns average per epoch (ws3)

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  Gx = runif(n=10000,min=0,max=2)
  Gy = runif(n=10000,min=1,max=3)
  Gz = runif(n=10000,min=0,max=2)
  data = cbind(Gx, Gy, Gz)
  colnames(data) = c("x", "y", "z")
  metrics2do = data.frame(do.bfen=TRUE,do.enmo=TRUE,do.lfenmo=FALSE,
  do.en=FALSE,do.hfen=FALSE,do.hfenplus=FALSE,do.mad=FALSE,do.anglex=FALSE,
  do.angley=FALSE,do.anglez=FALSE,do.roll_med_acc_x=FALSE,
  do.roll_med_acc_y=FALSE,do.roll_med_acc_z=FALSE,
  do.dev_roll_med_acc_x=FALSE,do.dev_roll_med_acc_y=FALSE,
  do.dev_roll_med_acc_z=FALSE,do.enmoa=FALSE,
  do.lfx=FALSE, do.lfy=FALSE, do.lfz=FALSE, 
  do.hfx=FALSE, do.hfy=FALSE, do.hfz=FALSE, 
  do.bfx=FALSE, do.bfy=FALSE, do.bfz=FALSE,
  do.zcx=FALSE, do.zcy=FALSE, do.zcz=FALSE, 
  do.brondcounts=FALSE, do.neishabouricounts=FALSE)
  
  extractedmetrics = g.applymetrics(data,n=4,sf=40,ws3=5,metrics2do)

function to estimate calibration error and make recommendation for addressing it

Description

Function starts by identifying ten second windows of non-movement. Next, the average acceleration per axis per window is used to estimate calibration error (offset and scaling) per axis. The function provides recommended correction factors to address the calibration error and a summary of the callibration procedure.

Usage

  g.calibrate(datafile, params_rawdata = c(), params_general = c(),
              params_cleaning = c(), inspectfileobject = c(), verbose = TRUE, ...)

Arguments

datafile

Name of accelerometer file

params_rawdata

See g.part1

params_general

See g.part1

params_cleaning

See g.part1

inspectfileobject

Output from the function g.inspectfile.

verbose

Boolean (default = TRUE). to indicate whether console message should be printed. Note that warnings and error are always printed and can be suppressed with suppressWarning() or suppressMessages().

...

Any argument used in the previous version of g.calibrate, which will now be used to overrule the arguments specified with the parameter objects.

Value

scale

scaling correction values, e.g. c(1,1,1)

offset

offset correction values, e.g. c(0,0,0)

tempoffset

correction values related to temperature, e.g. c(0,0,0)

cal.error.start

absolute difference between Euclidean norm during all non-movement windows and 1 g before autocalibration

cal.error.end

absolute difference between Euclidean norm during all non-movement windows and 1 g after autocalibration

spheredata

average, standard deviation, Euclidean norm and temperature (if available) for all ten second non-movement windows as used for the autocalibration procedure

npoints

number of 10 second no-movement windows used to populate the sphere

nhoursused

number of hours of measurement data scanned to find the ten second time windows with no movement

meantempcal

mean temperature corresponding to the data as used for autocalibration. Only applies to data where temperate data is collected and available to GGIR, such as GENEActiv, Axivity, and in some instances ad-hoc .csv data.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Zhou Fang

References

Examples

  ## Not run: 
    datafile = "C:/myfolder/testfile.bin"
    
    #Apply autocalibration:
    C = g.calibrate(datafile)
    print(C$scale)
    print(C$offset)
  
## End(Not run)

Function to read activity log and make it useful for the rest of GGIR.

Description

Function to read activity log and convert it into data.frame that has for each ID and date a different qwindow vector.

Usage

  g.conv.actlog(qwindow, qwindow_dateformat="%d-%m-%Y", epochSize = 5)	

Arguments

qwindow

Path to csv file with activity log. Expected format of the activity diary is: First column headers followed by one row per recording, first column is recording ID, which needs to match with the ID GGIR extracts from the accelerometer file. Followed by date column in format "23-04-2017", where date format is specified by argument qwindow_dateformat (below). Use the character combination date, Date or DATE in the column name. This is followed by one or multiple columns with start times for the activity types in that day format in hours:minutes:seconds. The header of the column will be used as label for each activity type. Insert a new date column before continuing with activity types for next day. Leave missing values empty. If an activitylog is used then individuals who do not appear in the activitylog will still be processed with value c(0,24). Dates with no activiy log data can be skipped, no need to have a column with the date followed by a column with the next date. If times in the activitylog are not multiple of the short window size (epoch length), the next epoch is considered (e.g., with epoch of 5 seconds, 8:00:02 will be redefined as 8:00:05 in the activity log).

qwindow_dateformat

Character specifying the date format used in the activity log.

epochSize

Short epoch size (first value of windowsizes in g.getmeta).

Value

Data.frame with column ID, date and qwindow, where each qwindow value is a qwindow vector

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Convert part 2 report to long format

Description

Not for direct access by used. This function is used inside g.report.part2 and convert2 part 2 report to long ormat if there are multiple segments per day

Usage

g.convert.part2.long(daySUMMARY)

Arguments

daySUMMARY

Object available inside g.report.part2

Value

Data.frame with long format version of daySUMMARY

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Converts sleep period information. Not intended for direct use

Description

Function to convert data into sleep period matrix part of g.part4.R. Not intended for direct use by package user

Usage

g.create.sp.mat(nsp,spo,sleepdet.t,daysleep=FALSE)

Arguments

nsp

Integer indicating the number of sleep periods

spo

Empty matrix with overview of sleep periods, 5 columns and as along as nps

sleepdet.t

Part of detected sleep from g.sib.det for one night and one sleep definition

daysleep

Boolean to indicator whether this person woke up after noon (daysleeper)

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Detect all midnights in a time series

Description

Detect all midnights in a time series

Usage

  g.detecmidnight(time,desiredtz, dayborder)

Arguments

time

Vector of timestamps, either in iso8601 or in POSIX format

desiredtz

See g.part2

dayborder

see g.analyse

Value

Output of the function is list containing the following objects:

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Assesses whether decimals in fileheader are stored with comma or dot separated decimals

Description

The function is used by g.readaccfile to assess how numeric data should be interpretted

Usage

  g.dotorcomma(inputfile, dformat, mon, ...)

Arguments

inputfile

full path to inputfile

dformat

Data format code: 1=.bin, 2=.csv, 3=.wav, 4=.cwa, 5=.csv for ad-hoc monitor brand

mon

Monitor code (accelorometer brand): 0=undefined, 1=GENEA, 2=GENEActiv, 3=Actigraph, 4=Axivity, 5=Movisense, 6=Verisense

...

Any input arguments needed for function read.myacc.csv if you are working with a non-standard csv formatted files.

Value

Character object showing how decimals are separated

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    decn = g.dotorcomma(inputfile="C:/myfile.bin",dformat=1,mon=2)
  
## End(Not run)

Extracts header variables from header object

Description

Function is not intended for direct interaction by package end user

Usage

g.extractheadervars(I)

Arguments

I

Object produced by g.inspectfile

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

data(data.inspectfile)
headervars = g.extractheadervars(I=data.inspectfile)

Fragmentation metrics from time series.

Description

The function is used by g.part5 to derive time series fragmentation metrics. The function assumes that NA values and nonwear time is accounted for before the data enters the function.

Usage

  g.fragmentation(frag.metrics = c("mean", "TP", "Gini", "power",
        "CoV", "NFragPM", "all"), LEVELS = c(), Lnames=c(), xmin=1, mode = "day")

Arguments

frag.metrics

Character with fragmentation metric to exract. Can be "mean", "TP", "Gini", "power", or "CoV", "NFragPM", or all the above metrics with "all". See details.

LEVELS

Numeric vector of behavioural level classes derived with identify_levels

Lnames

Character vector with names of classes used in LEVELS, see details.

xmin

Numeric scalar to indicate the minimum recordable fragment length. In g.part5 this is derived from the epoch length.

mode

Character to indicate whether input data is daytime ("day") or sleep period time ("spt").

Details

See package vignette for description of fragmentation metrics. In short, abbreviation "TP" refers to transition probality metrics, abbreviation "CoV" refers to Coefficient of Variance, and metric "NFragPM" refers to the Number of fragments per minute.

Regarding the Lnames argument. The class names included in this are categorised as follows:

Value

List with Character object showing how decimals are separated

TP_PA2IN

Transition probability physical activity to inactivity

.

TP_IN2PA

Transition probability physical inactivity to activity

Nfrag_IN2LIPA

Number of inacitivty fragments succeeded by LIPA (light physical activity)

TP_IN2LIPA

Transition probability physical inactivity to LIPA

Nfrag_IN2MVPA

Number of inacitivty fragments succeeded by MVPA (moderate or vigorous physical activity)

TP_IN2MVPA

Transition probability physical inactivity to MVPA

Nfrag_MVPA

Number of MVPA fragments

Nfrag_LIPA

Number of LIPA fragments

mean_dur_MVPA

mean MVPA fragment duration

mean_dur_LIPA

mean LIPA fragment duration

Nfrag_IN

Number of inactivity fragments

Nfrag_PA

Number of activity fragments

mean_dur_IN

mean duration inactivity fragments

mean_dur_PA

mean duration activity fragments

Gini_dur_IN

Gini index corresponding to inactivity fragment durations

Gini_dur_PA

Gini index corresponding to activity fragment durations

CoV_dur_IN

Coefficient of Variance corresponding to inactivity fragment durations

CoV_dur_PA

Coefficient of Variance corresponding to activity fragment durations

alpha_dur_IN

Alpha of the fitted power distribution through inactivity fragment durations

alpha_dur_PA

Alpha of the fitted power distribution through activity fragment durations

x0.5_dur_IN

x0.5 corresponding to alpha_dur_IN

x0.5_dur_PA

x0.5 corresponding to alpha_dur_PA

W0.5_dur_IN

W0.5 corresponding to alpha_dur_IN

W0.5_dur_PA

W0.5 corresponding to alpha_dur_PA

NFragPM_IN

Number of IN fragments per minutes in IN

NFragPM_PA

Number of PA fragments per minutes in PA

SD_dur_IN

Standard deviation in the duration of inactivity fragments

SD_dur_PA

Standard deviation in the duration of physical activity fragments

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

## Not run: 
    x = c(6, 5, 6, 7, 6, 6, 7, 6, 6, 5, 6, 6, 6, 5, 7, 6, 6, 5, 5, 5, 6, 7, 6,
        6, 6, 6, 7, 6, 5, 5, 5, 5, 5, 6, 6, 6, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
        7, 7, 6, 5, 6, 5, 6, 5, rep(12, 11), 5, 6, 6, 6, 5, 6, rep(9, 14), 6,
        5, 7, 7, 6, 7, 7, 7, 6, 6, 6, 5, 6, 5, 5, 5, 6, 5, 5, 5, 5, 5, 5, 5)
  Lnames = c("spt_sleep", "spt_wake_IN", "spt_wake_LIG", "spt_wake_MOD",
            "spt_wake_VIG", "day_IN_unbt", "day_LIG_unbt", "day_MOD_unbt",
            "day_VIG_unbt", "day_MVPA_bts_10", "day_IN_bts_30",
             "day_IN_bts_10_30", "day_LIG_bts_10")
  out = g.fragmentation(frag.metrics = "all",
                        LEVELS = x,
                        Lnames=Lnames)
## End(Not run)

Extract M5 and L5 from time series

Description

Extract M5 and L5 from time series, function used by g.analyse and not intended for direct use by package user. Please see g.analyse for further clarification on functionalities

Usage

  g.getM5L5(varnum, epochSize, t0_LFMF, t1_LFMF, M5L5res, winhr, qM5L5 = c(), 
            iglevels = c(), MX.ig.min.dur = 10, UnitReScale = 1000)	

Arguments

varnum

Numeric vector of epoch values

epochSize

Small epoch size in seconds

t0_LFMF

Start hour of the day for the M5L5 analyses, e.g. 0 for midnight

t1_LFMF

End hour of the day for the M5L5 analyses, e.g. 24 for midnight

M5L5res

Resolution of hte M5L5 analyses in minutes

winhr

windowsize of M5L5 analyses, e.g. 5 hours

qM5L5

Percentiles (quantiles) to be calculated over L5 and M5 window.

iglevels

See g.analyse. If provided then the intensity gradient will be calculated for all MX windows larger or equal than argument MX.ig.min.dur

MX.ig.min.dur

Minimum MX duration needed in order for intensity gradient to be calculated

UnitReScale

Numeric value with which acceleration values are multiple to rescale

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    data(data.getmeta)
    g.getM5L5(varnum=data.getmeta,ws3=5,t0_LFMF=0,t1_LFMF=24,M5L5res=10,winhr=5)
  
## End(Not run)

function to calculate bouts from vector of binary classes

Description

To detect bouts of behaviour in time series. The function is used by g.analyse

Usage

  g.getbout(x, boutduration, boutcriter = 0.8, ws3 = 5)

Arguments

x

vector of zeros and/or ones to be screened for bouts of ones

boutduration

duration of bout in epochs

boutcriter

Minimum percentage of boutduration for which the epoch values are expected to meet the threshold criterium

ws3

epoch length in seconds, only needed for bout.metric =3, because it needs to measure how many epochs equal 1 minute breaks

Value

Vector with binary numbers indicator where bouts where detected

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Jairo Hidalgo Migueles

Examples

  y = g.getbout(x=round(runif(1000, 0.4, 1)), boutduration = 120, boutcriter=0.9,
    ws3 = 5)

Function to extract meta-data (features) from data in accelerometer file

Description

Reads a accelerometer file in blocks, extracts various features and stores average feature value per short or long epoch. Acceleration and angle metrics are stored at short epoch length. The non-wear indication score, the clipping score, temperature (if available), light (if available), and Euclidean norm are stored at long epoch length. The function has been designed and thoroughly tested with accelerometer files from GENEA and GENEActiv bin files. Further, the function should be able to cope with ActiGraph gt3x and csv files, Axivity cwa and csv files, Movisens bin files, and ad-hoc csv files read through the read.myacc.csv function.

Usage

  g.getmeta(datafile, params_metrics = c(), params_rawdata = c(),
                     params_general = c(), params_cleaning = c(), daylimit = FALSE,
                     offset = c(0, 0, 0), scale = c(1, 1, 1), tempoffset = c(0, 0, 0),
                     meantempcal = c(), myfun = c(), inspectfileobject = c(), 
                     verbose = TRUE, ...)

Arguments

datafile

name of accelerometer file

params_metrics

See details in GGIR.

params_rawdata

See details in GGIR.

params_general

See details in GGIR.

params_cleaning

See details in GGIR.

daylimit

number of days to limit (roughly), if set to FALSE no daylimit will be applied

offset

offset correction value per axis, usage: value = scale(value,center = -offset, scale = 1/scale)

scale

scaling correction value per axis, usage: value = scale(value,center = -offset, scale = 1/scale)

tempoffset

temperature offset correction value per axis, usage: value = scale(value,center = -offset, scale = 1/scale) + scale(temperature, center = rep(averagetemperate,3), scale = 1/tempoffset)

meantempcal

mean temperature corresponding to the data as used for autocalibration. If autocalibration is not done or if temperature was not available then leave blank (default)

myfun

External function object to be applied to raw data. See details applyExtFunction.

inspectfileobject

Output from the function g.inspectfile.

verbose

Boolean (default = TRUE). to indicate whether console message should be printed. Note that warnings and error are always printed and can be suppressed with suppressWarning() or suppressMessages().

...

Any argument used in the previous version of g.getmeta, which will now be used to overrule the arguments specified with the parameter objects.

Value

metalong

dataframe with long epoch meta-data: EN, non-wear score, clipping score, temperature

metashort

dataframe with short epoch meta-data: timestamp and metric

tooshort

indicator of whether file was too short for processing (TRUE or FALSE)

corrupt

indicator of whether file was considered corrupt (TRUE or FALSE)

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  ## Not run: 
    datafile = "C:/myfolder/testfile.bin"

    #Extract meta-data:
    M = g.getmeta(datafile)

    #Inspect first couple of rows of long epoch length meta data:
    print(M$metalong[1:5,])

    #Inspect first couple of rows of short epoch length meta data:
    print(M$metalong[1:5,])
  
## End(Not run)

Extract start time of a measurement

Description

Extract start time of a measurement. GGIR calculates all timestamps by using the first timestamp and sample frequency. Not intended for direct use by package user

Usage

  g.getstarttime(datafile, data, mon, dformat, desiredtz,
  configtz = NULL)

Arguments

datafile

Full path to data file

data

Data part of g.readaccfile output

mon

Same as in g.dotorcomma

dformat

Same as in g.dotorcomma

desiredtz

Same as in g.dotorcomma

configtz

Same as in g.dotorcomma

Value

The starttime

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Function to identify invalid periods in the meta-data as generated by g.getmeta and to impute these invalid periods with the average of similar timepoints on other days of the measurement

Description

Functions takes the output from g.getmeta and information about the study protocol to label impute invalid time segments in the data.

Usage

  g.impute(M, I, params_cleaning = c(), desiredtz = "", dayborder = 0,
            TimeSegments2Zero = c(), acc.metric = "ENMO", ID, 
            qwindowImp = c(), ...)

Arguments

M

output from g.getmeta

I

output from g.inspectfile

params_cleaning

See g.part1

desiredtz

See g.part1

dayborder

See g.part1

TimeSegments2Zero

Optional data.frame to specify which time segments need to be ignored for the imputation, and acceleration metrics to be imputed by zeros. The data.frame is expected to contain two columns named windowstart and windowend, with the start- and end time of the time segment in POSIXlt class.

acc.metric

See GGIR

ID

ID extracted in g.part2.

qwindowImp

qwindow object as documented in See GGIR. If qwindow is based on a diary then the qwindow object is assumed to only include the values for the current participant ID.

...

Any argument used in the previous version of g.impute, which will now be used to overrule the arguments specified with the parameter objects.

Value

metashort

imputed short epoch variables

rout

matrix to clarify when data was imputed for each long epoch time window and the reason for imputation. Value = 1 indicates imputation. Columns 1 = monitor non wear, column 2 = clipping, column 3 = additional nonwear, column 4 = protocol based exclusion and column5 = sum of column 1,2,3 and 4.

averageday

matrix with n columns for n metrics values and m rows for m short epoch time windows in an average 24 hours period

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    #inspect file:
    I = g.inspectfile(datafile)
    #autocalibration:
    C = g.calibrate(datafile) 
    #get meta-data:
    M = g.getmeta(datafile)
  
## End(Not run)
  data(data.getmeta)
  data(data.inspectfile)
  #impute meta-data:
  IMP = g.impute(M=data.getmeta, I=data.inspectfile)

Impute gaps in three axis raw accelerometer data

Description

Removes all sample with a zero in each of the three axes, and then (as default) imputes time gaps by the last recorded value per axis normalised to 1 _g_

Usage

  g.imputeTimegaps(x, sf, k = 0.25, impute = TRUE, 
                   PreviousLastValue = c(0,0,1), 
                   PreviousLastTime = NULL, epochsize = NULL)

Arguments

x

Data.frame with raw accelerometer data, and a timestamp column with millisecond resolution.

sf

Sample frequency in Hertz

k

Minimum time gap length to be imputed

impute

Boolean to indicate whether the time gaps identified should be imputed

PreviousLastValue

Automatically identified last value in previous chunk of data read.

PreviousLastTime

Automatically identified last timestamp in previous chunk of data read.

epochsize

Numeric vector of length two, with short and long epoch sizes.

Value

List including: - x, data.frame based on input x with timegaps imputed (as default) or with recordings with 0 values in the three axes removed (if impute = FALSE) - QClog, data.frame with information on the number of time gaps found and the total time imputed in minutes

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


function to inspect accelerometer file for brand, sample frequency and header

Description

Inspects accelerometer file for key information, including: monitor brand, sample frequency and file header

Usage

g.inspectfile(datafile, desiredtz = "", params_rawdata = c(),
                         configtz = c(), ...)

Arguments

datafile

name of data file

desiredtz

Desired timezone, see documentation g.getmeta

params_rawdata

See g.part1

configtz

...

...

Any argument used in the previous version of g.getmeta, which will now be used to overrule the arguments specified with the parameter objects.

Value

header

fileheader

monn

monitor name (genea, geneactive)

monc

monitor brand code (0 - ad-hoc file format, 1 = genea (non-commercial), 2 = GENEActive, 3 = actigraph, 4 = Axivity (AX3, AX6), 5 = Movisense, 6 = Verisense)

dformn

data format name, e.g bin, csv, cwa, gt3x

dformc

data format code (1 = .bin, 2 = .csv, 3 = .wav, 4 = .cwa, 5 = ad-hoc .csv, 6 = .gt3x)

sf

samplefrequency in Hertz

filename

filename

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Intensity gradient calculation

Description

Calculates the intensity gradient based on Rowlands et al. 2018. The function assumes that the user has already calculated the value distribution.

Usage

g.intensitygradient(x,y)

Arguments

x

Numeric vector of mid-points of the bins (mg)

y

Numeric vector of time spent in bins (minutes)

Value

y_intercept

y-intercept of a linear regression line in log-log space

gradient

Beta coefficient of a linear regression line in log-log space

rsquared

R squared of x and y values in log-log space

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Rowlands A, Edwardson CL, et al. (2018) Beyond Cut Points: Accelerometer Metrics that Capture the Physical Activity Profile. MSSE 50(6):1. doi:10.1249/MSS.0000000000001561


Load and clean sleeplog information

Description

Loads sleeplog from a csv input file and applies sanity checks before storing the output in a dataframe

Usage

  g.loadlog(loglocation = c(), coln1 = c(), colid = c(),
            sleeplogsep = ",", meta.sleep.folder = c(),
            desiredtz = "")

Arguments

loglocation

Location of the spreadsheet (csv) with sleep log information. See package vignette for explanation on expected format

coln1

Column number in the sleep log spreadsheet where the onset of the first night starts

colid

Column number in the sleep log spreadsheet in which the participant ID code is stored (default = 1)

sleeplogsep

Value used as sep argument for reading sleeplog csv file, usually "," or ";". This argument has been deprecated.

meta.sleep.folder

Path to part3 milestone data, only specify if sleeplog is in advanced format.

desiredtz

See g.part4

Value

Data frame with sleeplog, which can be either in basic format or in advanced format. See GGIR package vignette for discussion of these two formats.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

## Not run: 
  sleeplog = g.loadlog(loglocation="C:/mysleeplog.csv",coln1=2,
  colid=1)

## End(Not run)

function to load and pre-process acceleration files

Description

Calls function g.getmeta and g.calibrate, and converts the output to .RData-format which will be the input for g.part2. Here, the function generates a folder structure to keep track of various output files. The reason why these g.part1 and g.part2 are not merged as one generic shell function is because g.part1 takes much longer to and involves only minor decisions of interest to the movement scientist. Function g.part2 on the other hand is relatively fast and comes with all the decisions that directly impact on the variables that are of interest to the movement scientist. Therefore, the user may want to run g.part1 overnight or on a computing cluster, while g.part2 can then be the main playing ground for the movement scientist. Function GGIR provides the main shell that allows for operating g.part1 and g.part2.

Usage

  g.part1(datadir = c(), metadatadir = c(), f0 = 1, f1 = c(),
          myfun = c(), params_metrics = c(), params_rawdata = c(),
          params_cleaning = c(), params_general = c(), verbose = TRUE, ...)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory where the output needs to be stored. Note that this function will attempt to create folders in this directory and uses those folder to keep output.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

myfun

External function object to be applied to raw data. See details applyExtFunction.

params_metrics

See details in GGIR.

params_rawdata

See details in GGIR.

params_cleaning

See details in GGIR.

params_general

See details in GGIR.

verbose

See details in GGIR.

...

If you are working with a non-standard csv formatted files, g.part1 also takes any input arguments needed for function read.myacc.csv and argument rmc.noise from get_nw_clip_block_params. First test these argument with function read.myacc.csv directly. To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Details

GGIR comes with many processing parameters, which have been thematically grouped in parameter objects (R list). By running print(load_params()) you can see the default values of all the parameter objects. When g.part 1 is used via GGIR you have the option to specifiy a configuration file, which will overrule the default parameter values. Further, as user you can set parameter values as input argument to both g.part1 and GGIR. Directly specified argument overrule the configuration file and default values.

See the GGIR package vignette or the details section in GGIR for a more elaborate overview of parameter objects and their usage across GGIR.

Value

The function provides no values, it only ensures that the output from other functions is stored in .RData(one file per accelerometer file) in folder structure

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  ## Not run: 
    datafile = "C:/myfolder/mydata"
    outputdir = "C:/myresults"
    g.part1(datadir,outputdir)
  
## End(Not run)

function to analyse and summarize pre-processed output from g.part1

Description

Loads the output from g.part1 and then applies g.impute and g.analyse, after which the output is converted to .RData-format which will be used by GGIR to generate reports. The variables in these reports are the same variables as described in g.analyse.

Usage

  g.part2(datadir = c(), metadatadir = c(), f0 = c(), f1 = c(),
        myfun = c(), params_cleaning = c(), params_247 = c(),
        params_phyact = c(), params_output = c(), params_general = c(),
        verbose = TRUE, ...)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

myfun

External function object to be applied to raw data. See details applyExtFunction.

params_cleaning

See details in GGIR.

params_247

See details in GGIR.

params_phyact

See details in GGIR.

params_output

See details in GGIR.

params_general

See details in GGIR.

verbose

See details in GGIR.

...

To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Details

GGIR comes with many processing parameters, which have been thematically grouped in parameter objects (R list). By running print(load_params()) you can see the default values of all the parameter objects. When g.part 2 is used via GGIR you have the option to specifiy a configuration file, which will overrule the default parameter values. Further, as user you can set parameter values as input argument to both g.part2 and GGIR. Directly specified argument overrule the configuration file and default values.

See the GGIR package vignette or the details section in GGIR for a more elaborate overview of parameter objects and their usage across GGIR.

Value

The function provides no values, it only ensures that other functions are called and that their output is stored in the folder structure as created with g.part1.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  ## Not run: 
    metadatadir = "C:/myresults/output_mystudy"
    g.part2(metadatadir)
  
## End(Not run)

Detection of sustained inactivity periods as needed for sleep detection in g.part4.

Description

Function called by function GGIR. It estimates the sustained inactivity periods in each day, which are used as input for g.part4 which then labels them as nocturnal sleep or day time sustained inactivity periods. Typical users should work with function GGIR only.

Usage

g.part3(metadatadir = c(), f0, f1, myfun = c(), 
  params_sleep = c(), params_metrics = c(), params_output = c(), 
  params_general = c(), verbose = TRUE,
  ...)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

myfun

External function object to be applied to raw data. See details applyExtFunction.

params_sleep

See details in GGIR.

params_metrics

See details in GGIR.

params_output

See details in GGIR.

params_general

See details in GGIR.

verbose

See details in GGIR.

...

To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Details

GGIR comes with many processing parameters, which have been thematically grouped in parameter objects (R list). By running print(load_params()) you can see the default values of all the parameter objects. When g.part 3 is used via GGIR you have the option to specifiy a configuration file, which will overrule the default parameter values. Further, as user you can set parameter values as input argument to both g.part3 and GGIR. Directly specified argument overrule the configuration file and default values.

See the GGIR package vignette or the details section in GGIR for a more elaborate overview of parameter objects and their usage across GGIR.

Value

The function provides no values, it only ensures that other functions are called and that their output is stored in .RData files.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  ## Not run: 
    metadatadir = "C:/myfolder/meta" # assumes that there is a subfolder in
    # metadatadir named 'basic' containing the output from g.part1
    g.part3(metadatadir=metadatadir, anglethreshold=5,
    timethreshold=5, overwrite=FALSE)
  
## End(Not run)

Labels detected sustained inactivity periods by g.part3 as either part of the Sleep Period Time window or not

Description

Combines output from g.part3 and guider information to estimate sleep variables. See vignette paragraph "Sleep and full day time-use analysis in GGIR" for an elaborate descript of the sleep detection.

Usage

 g.part4(datadir = c(), metadatadir = c(), f0 = f0, f1 = f1, params_sleep = c(), 
    params_metrics = c(),  params_cleaning = c(), params_output = c(),
                   params_general = c(), verbose = TRUE, ...)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

params_sleep

List of parameters used for sleep analysis (GGIR part 3, 4, and 5): see documentation g.part3.

params_metrics

List of parameters used for metrics extraction (GGIR part 1): see documentation g.part1.

params_cleaning

See details in GGIR.

params_output

See details in GGIR.

params_general

See details in GGIR.

verbose

See details in GGIR.

...

To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Value

The function does not produce values but generates an RData file in the milestone subfolder ms4.out which incudes a dataframe named nightsummary. This dataframe is used in g.report.part4 to create two reports one per night and one per person. See package vignette paragraph "Output part 4" for description of all the variables.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

References

Examples

  ## Not run: 
    metadatadir = "C:/myfolder/meta" # assumes that there is a subfolder in
    # metadatadir named 'ms3.out' containing the output from g.part3
    g.part4(metadatadir=metadatadir)
  
## End(Not run)

Extracts ID from filename and finds matching rows in sleeplog

Description

Extracts ID from filename and finds matching rows in sleeplog. Function not designed for direct use by GGIR users.

Usage

  g.part4_extractid(idloc, fname, dolog, sleeplog, accid = c())

Arguments

idloc

See g.part4

fname

Full patth to filename

dolog

Boolean to indicate whether to rely on a sleeplog

sleeplog

Sleeplog data.frame passed on from g.part4

accid

ID extracted from the acceleration file in GGIR part3. If not available leave blank.

Value

List with accid the ID and matching_indices_sleeplog a vector with matching row indices in the sleeplog

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Merge output from physical activity and sleep analysis into one report

Description

Function to merge the output from g.part2 and g.part4 into one report enhanced with profiling of sleep and physical activity stratified across intensity levels and based on bouted periods as well as non-bouted periods.

Usage

g.part5(datadir = c(), metadatadir = c(), f0 = c(), f1 = c(),
                   params_sleep = c(), params_metrics = c(),
                   params_247 = c(), params_phyact = c(), 
                   params_cleaning = c(), params_output = c(),
                   params_general = c(), verbose = TRUE, ...)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

params_sleep

See details in GGIR.

params_metrics

See details in GGIR.

params_247

See details in GGIR.

params_phyact

See details in GGIR.

params_cleaning

See details in GGIR.

params_output

See details in GGIR.

params_general

See details in GGIR.

verbose

See details in GGIR.

...

To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Value

The function does not produce values but generates an RData file in the milestone subfolder ms5.out which incudes a dataframe named output. This dataframe is used in g.report.part5 to create two reports one per day and one per person. See package vignette paragraph "Output part 5" for description of all the variables.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    metadatadir = "C:/myfolder/meta"
    g.part5(metadatadir=metadatadir)
  
## End(Not run)

Adds first wake if it is missing in part 4 output.

Description

Not intended for direct use by GGIR users. Adds first wake if it is missing in part 4 output as part of g.part5.

Usage

  g.part5.addfirstwake(ts, summarysleep, nightsi, sleeplog,
  ID, Nepochsinhour, SPTE_end)

Arguments

ts

Data.frame object as passed on from g.part5

summarysleep

Data.frame object as passed on from g.part5 with sleep summary information from g.part4.

nightsi

Vector with indices for the nights

sleeplog

Data.frame with all sleeplog information

ID

Participant ID

Nepochsinhour

Number of epochs in an hour

SPTE_end

Sleep period time end index

Value

Data.frame ts updated with first wakeup time

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Adds the sustained inactivity bout to the ts series.

Description

Not intended for direct use by GGIR users. Adds the sustained inactivity bout to the ts series as part of g.part5.

Usage

  g.part5.addsib(ts, epochSize, part3_output, desiredtz,
              sibDefinition, nightsi)

Arguments

ts

Data.frame object as passed on from g.part5

epochSize

Short epoch size in seconds

part3_output

Segment of part 3 output relevant for current sleep definition

desiredtz

see GGIR

sibDefinition

Character to indicate definition of sib (sustained inactivity bout)

nightsi

Vector with indices for the midnights

Value

Data.frame ts

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Analyse rest (internal function)

Description

Analyses overlap self-reported napping, non-wear and sib. Internal function not intended for direct use by GGIR end-user.

Usage

  g.part5.analyseRest(sibreport = NULL, dsummary = NULL,
                                ds_names = NULL, fi = NULL,
                                di = NULL, ts = NULL, tz = NULL,
                                params_sleep = NULL)

Arguments

sibreport

sibreport data.frame produced by g.sibreport

dsummary

matrix created internally by g.part5

ds_names

character vector with variable names corresponding to dsummary created internally by g.part5

fi

Numeric scalar to indicate variable index, created internally by g.part5

di

Numeric scalar to indicate recording index, created internally by g.part5

ts

Data.frame with time series object passed on from g.part5_analyseSegment and g.part5,

tz

Timezone database name

params_sleep

See GGIR

Value

List with updated objects dsummary, ds_names, fi, and di

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Classify Naps from identified sustained inactivty bouts

Description

Classify Naps from identified sustained inactivty bouts, based on model that was originally trained with hip-worn accelerometer data in 3-3.5 year olds. Assume that metric ENMO is used and HASIB.algo is set to vanHees2015.

Usage

  g.part5.classifyNaps(sibreport = c(), desiredtz = "", 
        possible_nap_window = c(9, 18),
        possible_nap_dur = c(15, 240),
        nap_model = "hip3yr", HASIB.algo = "vanHees2015")

Arguments

sibreport

Object generated by g.sibreport

desiredtz

See g.getmeta.

possible_nap_window

Numeric vector of length two with range in clock hours during which naps are assumed to take place.

possible_nap_dur

Numeric vector of length two with range in duration (minutes) of a nap.

nap_model

Character to specify classification model. Currently the only option is "hip3yr", which corresponds to a model trained with hip data in 3-3.5 olds trained with parent diary data.

HASIB.algo

See g.part3.

Value

Data.frame with classified naps and newly detected non-wear periods.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Fix missing night in part 4 output

Description

Not intended for direct use by GGIR users. Defines when day windows start and end as part of g.part5.

Usage

  g.part5.definedays(nightsi, wi, indjump, nightsi_bu, 
                     epochSize, qqq_backup = c(), ts,
                     timewindowi, Nwindows, qwindow, ID = NULL,
                     dayborder = 0)

Arguments

nightsi

Vector with indices for the midnights

wi

Numeric to indicate window number

indjump

Number of indices to jump

nightsi_bu

See argument nightsi this is a backup of this object

epochSize

Numeric epoch size in seconds

qqq_backup

Backup of qqq object, which holds the start and end indices of a window

ts

Data.frame with time series

timewindowi

Timewindow definition either "MM" or "WW"

Nwindows

Number of windows in the data

qwindow

qwindow argument

ID

ID of participant

dayborder

dayborder argument

Value

List of qqq and qqq_backup

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Fix missing night in part 4 output

Description

Not intended for direct use by GGIR users. If a night is missing in the part4 output then this function tries to fix as part of g.part5.

Usage

  g.part5.fixmissingnight(summarysleep, sleeplog = c(), ID)

Arguments

summarysleep

Object produced by g.part4

sleeplog

Sleeplog object as passed on from g.part5

ID

ID of participant

Value

Corrected summarysleep_tmp2 object.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Check lux values for extremes and imputes or removes them

Description

Extreme values are imputed by mean of neightbours if they occur isolated or in a sequence of two, and removed if they occure in a sequence of 3 or longer.

Usage

  g.part5.handle_lux_extremes(lux)

Arguments

lux

Vector with lux values

Value

List of imputed lux values and a vector with matching length named correction_log indicating which timestamps where imputed (value=1), replaced by NA (value=2) or untouched (value=0).

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Extract key lux variables per segment of the data.

Description

Extracts per segment of the day: mean lux, time above 1000 lux, time awake, and time LUX imputed. Function not intended for direct use by package user.

Usage

  g.part5.lux_persegment(ts, sse, LUX_day_segments, epochSize, desiredtz = "")

Arguments

ts

Data.frame with time series

sse

Indices corresponding to the current time window (e.g. MM or WW)

LUX_day_segments

See GGIR

epochSize

Numeric epoch size in seconds

desiredtz

See GGIR

Value

List with values (vector) of the derived variables and corresponding names (vector).

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Identify wake and sleepperiod window timing

Description

Not intended for direct use by GGIR users. Labels timing of wakeing up and sleep onset as part of g.part5.

Usage

  g.part5.onsetwaketiming(qqq, ts, min, sec, hour, timewindowi)

Arguments

qqq

Start and end index of window to analyses

ts

Data.frame with time series as created in g.part5

min

Numeric vector with minute values

sec

Numeric vector with second values

hour

Numeric vector with hour values

timewindowi

Character to indicate what timewindow definition is used either "MM" or "WW"

Value

A list with objects: wake, onset, wakei, onseti, skiponset, and skipwake.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Saves part 5 time series to csv files

Description

Not intended for direct use by GGIR users. Saves part 5 time series to csv files as part of g.part5.

Usage

  g.part5.savetimeseries(ts, LEVELS, desiredtz, rawlevels_fname,
                            DaCleanFile = NULL,
                            includedaycrit.part5 = 2/3,
                            includenightcrit.part5 = 0,
                            ID = NULL,
                            params_output,
                            params_247 = NULL,
                            Lnames = NULL, timewindow = NULL,
                            filename = "")

Arguments

ts

Data.frame with time series

LEVELS

As produced as one of the objects in the output of identify_levels

desiredtz

See GGIR.

rawlevels_fname

Path to the file where the output (time series) should be stored

DaCleanFile

Content of data_cleaning_file as documented in g.report.part5. Only used in this function if save_ms5rawlevels is TRUE, and it only affects the time series files stored.

includedaycrit.part5

See GGIR. Only used in this function if save_ms5rawlevels is TRUE, and it only affects the time series files stored.

includenightcrit.part5

See GGIR. Only used in this function if save_ms5rawlevels is TRUE, and it only affects the time series files stored.

ID

If data_cleaning_file is used then this argument specifies which participant ID the data correspond with.

params_output

Parameters object, see GGIR

params_247

See GGIR

Lnames

Level names as passed on from identify_levels, these are the names corresponding the ID of the behavioural classes as stored in column class_id.

timewindow

See GGIR

filename

Character (default = "") indicating the name of the accelerometer data file that was used as input. This name will be stored inside the time series output file.

Value

Function does not provide output, it only prepare data for saving and saves it to a file. For documention on columns see main vignette.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Label wake and sleepperiod window

Description

Not intended for direct use by GGIR users. Label wake and sleepperiod window as part of g.part5.

Usage

  g.part5.wakesleepwindows(ts, part4_output, desiredtz,
                    nightsi, sleeplog, epochSize,ID, Nepochsinhour)

Arguments

ts

data.frame with time series

part4_output

cleaned output from part 4

desiredtz

GGIR

nightsi

vector with indices for the midnights

sleeplog

Data.frame with sleeplog information as loaded by g.loadlog

epochSize

Short epochsize in seconds

ID

ID of the participant

Nepochsinhour

Number of epochs in an hour

Value

Object ts

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Analyses the time series per time segment for part 5

Description

Not intended for direct use by GGIR users, part of g.part5.

Usage

  g.part5_analyseSegment(indexlog, timeList, levelList,
                                  segments,
                                  segments_names,
                                  dsummary, ds_names,
                                  params_general, params_output,
                                  params_sleep, params_247,
                                  params_phyact,
                                  sumSleep, sibDef,
                                  fullFilename,
                                  add_one_day_to_next_date,
                                  lightpeak_available,
                                  tail_expansion_log,
                                  foldernamei, sibreport = NULL)

Arguments

indexlog

List of objects related to indices of window, file, and segment that are passed on from g.part5 to aid selecting time segments or keeping track of where in file the code is.

timeList

List of objects related to time series passed on from g.part5.

levelList

List of objects related to intensity levels passed on from g.part5.

segments

List produced by g.part5

segments_names

Vector produced by g.part5

dsummary

Matrix to hold all daysummary (and segment summary)

ds_names

Character vector with column names of the dsummary matrix. The code collects these separately in this vector and assigns them at the end.

params_general

See GGIR

params_output

See GGIR

params_sleep

See GGIR

params_247

See GGIR

params_phyact

See GGIR

sumSleep

Section of data.frame produced by g.part4 passed on from g.part5.

sibDef

Character to identify sib definition.

fullFilename

Character with full filename being processed

add_one_day_to_next_date

Boolean to indicate whether one day should be added to next date

lightpeak_available

Boolean to indicate whether light peak is available

tail_expansion_log

Object generated in g.part1 and passed on to g.part5 when argument recordingEndSleepHour is used.

foldernamei

Character with folder name in which the data file is stored.

sibreport

Sibreport object as passed on from g.part5

Value

List with objects: indexlog, timeList, and the matrix with the prelimenary results and column names (dsummary and ds_names, see input arguments above)


Initialise time series data from for part 5

Description

Initialise time series dataframe ts, part of g.part5.

Usage

  g.part5_initialise_ts(IMP, M, params_247, params_general, longitudinal_axis = c())

Arguments

IMP

Object derived from g.part2

M

Object derived from g.part1.

params_247

See GGIR

params_general

See GGIR

longitudinal_axis

As passed on from g.part5, which could be specified by user or estimated from hip data in part 2.

Value

Data.frame ts


Perform temporal pattern analyses

Description

This function aims to facilitate time-pattern analysis building on the labelled time series derived in GGIR part 5

Usage

g.part6(datadir = c(), metadatadir = c(), f0 = c(), f1 = c(),
                   params_general = c(), params_phyact = c(), params_247 = c(),
                   params_cleaning = c(), verbose = TRUE, ...)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

params_general

See details in GGIR.

params_phyact

See details in GGIR.

params_247

See details in GGIR.

params_cleaning

See details in GGIR.

verbose

See details in GGIR.

...

To ensure compatibility with R scripts written for older GGIR versions, the user can also provide parameters listed in the params_ objects as direct argument.

Value

The function does not produce values but generates an RData file in the milestone subfolder ms6.out which incudes ... (TO BE COMPLETED). This dataframe is used in g.report.part6 to create reports. See package vignette paragraph (TO BE COMPLETED) for description of all the variables.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    metadatadir = "C:/myfolder/meta"
    g.part6(metadatadir=metadatadir)
  
## End(Not run)

function to generate a plot for quality check purposes

Description

Function takes meta-data as generated by g.getmeta and g.impute to create a visual representation of imputed time periods

Usage

g.plot(IMP, M, I, durplot)

Arguments

IMP

output from g.impute

M

output from g.getmeta

I

output from g.inspectfile

durplot

number of days to plot

Value

function only produces a plot, no values

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

## Not run: 
  #inspect file:
  I = g.inspectfile(datafile)
  
  #autocalibration:
  C = g.calibrate(datafile) 
  
  #get meta-data:
  M = g.getmeta(datafile)

## End(Not run)
data(data.getmeta)
data(data.inspectfile)

#impute meta-data:
IMP = g.impute(M = data.getmeta, I = data.inspectfile, strategy = 1,
hrs.del.start = 0, hrs.del.end = 0, maxdur = 0)

#plot data
g.plot(IMP, M = data.getmeta, I = data.inspectfile, durplot=4)

Generate user-friendly visual report. The first part of the report summarizes important daily metrics in bar plot format. The second part of the report shows the raw data and annotations in 24-hr periods. Angle-z is shown with sleep annotations during the SPT (sleep period time) window. ENMO is shown with daytime inactivity and PA (physical activity) annotations in the lower section of each 24-hr plot. The PA annotations are based on a 10 minute bout metric and 80 of a 10 minute bout of MVPA. Vigorous PA is a short window of time above threshold.vig that is part of a bout of MVPA. Light PA is a short window of time above threshold.lig that is part of a bout of light PA.

Description

Function called by GGIR to generate report. Not intended for direct use by user

Usage

  g.plot5(metadatadir = c(), dofirstpage = FALSE, viewingwindow = 1,
  f0 = c(), f1 = c(), overwrite = FALSE, metric="ENMO",desiredtz = "",
  threshold.lig = 30, threshold.mod = 100, threshold.vig = 400, 
  visualreport_without_invalid = TRUE, includedaycrit = 0.66, includenightcrit = 0.66,
  verbose = TRUE)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

dofirstpage

Boolean to indicate whether a first page with historgrams summarizing the whole measurement should be added

viewingwindow

See GGIR

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

overwrite

See GGIR

metric

Which one of the metrics do you want to consider to describe behaviour. The metric of interest need to be calculated in M (see g.part1)

desiredtz

See GGIR

threshold.lig

See GGIR

threshold.mod

See GGIR

threshold.vig

See GGIR

visualreport_without_invalid

See GGIR

includenightcrit

See GGIR

includedaycrit

See GGIR

verbose

See GGIR

Value

No values, this function only generates a plot

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Matthew R Patterson <mpatterson@shimmersensing.com>

Examples

  ## Not run: 
    # generate plots for the first 10 files:
    g.plot5(metadatadir="C:/output_mystudy/meta/basic",dofirstpage=TRUE,
    viewingwindow = 1,f0=1,f1=10,overwrite=FALSE,desiredtz = "Europe/London",
    threshold.lig,threshold.mod,threshold.vig)
  
## End(Not run)

Generic functiont to read large blocks of accelerometer data

Description

The function is used by g.getmeta and g.calibrate to read large blocks of the accelerometer file, which are processed and then deleted from memory. This is needed for memory management.

Usage

  g.readaccfile(filename, blocksize, blocknumber, filequality,
                           ws, PreviousEndPage = 1, inspectfileobject = c(),
                           PreviousLastValue = c(0,0,1), PreviousLastTime = NULL,
                           params_rawdata = c(), params_general = c(), header = NULL, ...)

Arguments

filename

filename

blocksize

Size of blocks (in file pages) to be read

blocknumber

Block number relative to start of file, starting with 1.

filequality

Single row dataframe with columns: filetooshort, filecorrupt, and filedoesnotholdday. All with the value TRUE or FALSE

ws

Larger windowsize for non-detection, see documentation g.part2

PreviousEndPage

Page number on which previous block ended (automatically assigned within g.getmeta and g.calibrate).

inspectfileobject

Output from the function g.inspectfile.

PreviousLastValue

Automatically identified last value in previous chunk of data read.

PreviousLastTime

Automatically identified last timestamp in previous chunk of data read.

params_rawdata

See g.part1

params_general

See g.part1

header

Header information that was extracted the previous time this file was read, to be re-used instead of being extracted again.

...

Any input arguments needed for function read.myacc.csv if you are working with a non-standard csv formatted files. Furter, any argument used in the previous version of g.readaccfile, which will now be used to overrule the arguments specified with the parameter objects.

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    filequality = data.frame(filetooshort = FALSE, filecorrupt = FALSE,
    filedoesnotholdday = FALSE)
    output = g.readaccfile(filename = "C:/myfile.bin", 
    blocksize = 20000, blocknumber = 1,
    selectdaysfile = c(), filequality = filequality,
    dayborder = 0, PreviousEndPage = c()) 
  
## End(Not run)

Reads the temperature from movisens files.

Description

Reads the temperature from movisens files, resamples it and adds it to the matrix where accelerations are stored

Usage

g.readtemp_movisens(datafile, from = c(), to = c(), acc_sf, acc_length,
                    interpolationType=1)

Arguments

datafile

Full path to the folder where the movisens bin files are stored. Note that movisens store a set of bin file in one folder per recording. GGIR will read the pertinent bin file to access to the temperature data.

from

Origin point to derive the temperature from movisens files (automatically calculated by GGIR)

to

End point to derive the temperature from movisens files (automatically calculated by GGIR)

acc_sf

Sample frequency of acceleration data

acc_length

number of acceleration data samples

interpolationType

Integer to indicate type of interpolation to be used when resampling time series (mainly relevant for Axivity sensors), 1=linear, 2=nearest neighbour.

Value

Data matrix with the temperature values resampled at 64 Hz.

Examples

## Not run: 
  P = g.readtemp_movisens(datafile, from = c(), to = c(), acc_sf = 64, acc_length = 3000)

## End(Not run)

Generate report from milestone data produced by g.part2

Description

Creates report from milestone data produced by g.part2. Not intended for direct use by package user

Usage

  g.report.part2(metadatadir = c(), f0 = c(), f1 = c(), maxdur = 0,
                  store.long = FALSE, params_output, myfun = c(), 
                  verbose = TRUE, desiredtz = "")

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

maxdur

see g.part2

store.long

Booelean to indicate whether output should stored in long format in addition to default wide format. Automatically turned to TRUE if using day segmentation with qwindow.

params_output

Parameters object, see GGIR

myfun

(Optional) List as documented in GGIR. g.report.part2 uses this object to extract the name of the external function being used, such that this can be reused in the output filenames.

verbose

See details in GGIR.

desiredtz

See details in GGIR.

Value

Function does not produce data, but only writes reports in csv format and visual reports in pdf format

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Generate report from milestone data produced by g.part4

Description

Creates report from milestone data produced by g.part4. Not intended for direct use by package user

Usage

g.report.part4(datadir = c(), metadatadir = c(), f0 = c(),
  f1 = c(), data_cleaning_file = c(),
  params_sleep, params_output, verbose = TRUE)

Arguments

datadir

Directory where the accelerometer files are stored, e.g. "C:/mydata", or list of accelerometer filenames and directories, e.g. c("C:/mydata/myfile1.bin", "C:/mydata/myfile2.bin").

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

data_cleaning_file

see GGIR

params_sleep

Parameters object, see GGIR

params_output

Parameters object, see GGIR

verbose

See details in GGIR.

Value

Function does not produce data, but only writes reports in csv format and a visual report in pdf.

The following files are stored in the root of the results folder: part4_nightsummary_sleep_cleaned.csv part4_summary_sleep_cleaned.csv

The following files are stored in the folder results/QC: part4_nightsummary_sleep_full.csv part4_summary_sleep_full.csv

If a sleeplog is used *_full.csv as stored in the QC folder includes estimates for all nights in the data, and *_cleaned.csv in the results folder includes estimates for all nights in the data excluding the nights that did not had a sleeplog entry or had no valid accelerometer data.

If a sleep log is not used then * _cleaned.csv includes the nights that are in *_full.csv excluding the nights with insufficient data.

If you have a study where the sleeplog was available for a subset of the participants, but you want to include all individuals in your analysis, then use the *_full.csv output and clean the night level data yourself by excluding rows with cleaningcode > 1 which are the cases where no or invalid accelerometer data was present.

The above means that for studies with missing sleeplog entries for some individuals and some nights using the *_full.csv output and excluding rows (nights) with cleaningcode > 1 will lead to the same as * _cleaned.csv plus sleep estimates for the nights with missing sleeplog, providing that there was enough accelerometer data for those nights.

In other words, *_cleaned.csv is perfect if you only want to rely on nights with a sleeplog or if you do not use a sleeplog at all. For all other scenarios We advise using the *_full.csv report and to clean it yourself.

See package vignette sections "Sleep analysis" and "Output part 4" for a more elaborative description of the sleep analysis and reporting.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Generate report from milestone data produced by g.part5

Description

Creates report from milestone data produced by g.part5. Not intended for direct use by package user

Usage

  g.report.part5(metadatadir = c(), f0 = c(), f1 = c(), loglocation = c(),
                          params_cleaning = NULL,
                          LUX_day_segments = c(), params_output,
                          verbose = TRUE)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

loglocation

see g.part4

params_cleaning

See details in GGIR.

LUX_day_segments

see g.part5

params_output

Parameters object, see GGIR

verbose

See details in GGIR.

Value

Function does not produce data, but only writes reports in csv format

The following files are stored in the root of the results folder: part5_daysummary_* part5_personsummary_*

The following files are stored in the folder results/QC: part5_daysummary_full_*

See package vignette paragraph "Waking-waking or 24 hour time-use analysis" and "Output part 5" for a more elaborative description of the full day time-use and analysis and reporting.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Generate data dictionary for reports from milestone data produced by g.part5

Description

Creates a data dictionary with the definitions of the outcomes exported in the reports from milestone data produced by g.part5. Not intended for direct use by package user.

Usage

g.report.part5_dictionary(metadatadir, params_output)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

params_output

Parameters object, see GGIR

Value

Function does not produce data, but only writes data dictionaries for the reports in csv format

The following files are stored in the root of the results folder: part5_dictionary_daysummary_* part5_dictionary_personsummary_*

Author(s)

Vincent T van Hees <v.vanhees@accelting.com> Jairo Hidalgo Migueles <jairo@jhmigueles.com>


Generate report from milestone data produced by g.part6

Description

Creates report from milestone data produced by g.part6. Not intended for direct use by package user

Usage

  g.report.part6(metadatadir = c(), f0 = c(), f1 = c(),
                          params_cleaning = NULL, params_output, 
                          verbose = TRUE)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

params_cleaning

See details in GGIR.

params_output

Parameters object, see GGIR

verbose

See details in GGIR.

Value

Function does not produce data, but only writes reports in csv format

The following files are stored in the root of the results folder: part6_summary.csv

See package vignette "HouseHoldCoanalysis".

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Wrapper function around function GGIR

Description

This function used to be the central function in the package, but has been renamed GGIR. You can still use function call g.shell.GGIR but all arguments will be passed on to function GGIR. We have done this to preserve consistency with older use cases of the GGIR package. All documentation can now be found in GGIR.

Usage

  g.shell.GGIR(...)

Arguments

...

Any of the parameters used by GGIR.

Value

The function provides no values, it only ensures that other functions are called and that their output is stored. See GGIR.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


sustiained inactivty bouts detection

Description

Detects sustiained inactivty bouts. Function not intended for direct use by package user

Usage

  g.sib.det(M, IMP, I, twd = c(-12, 12),
             acc.metric = "ENMO", desiredtz = "",
             myfun=c(), sensor.location = "wrist", params_sleep = c(), zc.scale = 1, ...)

Arguments

M

Object produced by g.getmeta

IMP

Object produced by g.impute

I

Object produced by g.inspectfile

twd

Vector of length 2, indicating the time window to consider as hours relative to midnight.

acc.metric

Which one of the metrics do you want to consider to analyze L5. The metric of interest need to be calculated in M (see g.part1)

desiredtz

See g.part3

myfun

External function object to be applied to raw data. See details applyExtFunction.

sensor.location

Character to indicate sensor location, default is wrist. If it is hip HDCZA algorithm also requires longitudinal axis of sensor to be between -45 and +45 degrees.

params_sleep

See g.part3

zc.scale

Used for zero-crossing counts only. Scaling factor to be applied after counts are calculated (GGIR part 3). See GGIR.

...

Any argument used in the previous version of g.sib.det, which will now be used to overrule the arguments specified with the parameter objects.

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Create plot of sustained inactivity bouts

Description

Function create plot of sustained inactivity bouts for quality check purposes as part of g.part3. Not intended for direct use by package user

Usage

  g.sib.plot(SLE, M, I, plottitle, nightsperpage=7, desiredtz="")

Arguments

SLE

Output from g.sib.det

M

Output from g.getmeta

I

Output from g.inspectfile

plottitle

Title to be used in the plot

nightsperpage

Number of nights to show per page

desiredtz

See g.part3

Value

Function has no output other than the plot

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


sustiained inactivty bouts detection

Description

Detects sustiained inactivty bouts. Function not intended for direct use by package user

Usage

  g.sib.sum(SLE,M,ignorenonwear=TRUE,desiredtz="")

Arguments

SLE

Output from g.sib.det

M

Object produced by g.getmeta

ignorenonwear

If TRUE then ignore detected monitor non-wear periods to avoid confusion between monitor non-wear time and sustained inactivity (default = TRUE)

desiredtz

See g.part3

Value

Dataframe with per night and per definition of sustained inactivity bouts the start and end time of each sustained inactivity bout

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Generate sustiained inactivty bouts report

Description

Generate sustained inactivity bout report. Function not intended for direct use by package user

Usage

  g.sibreport(ts, ID, epochlength, logs_diaries=c(), desiredtz="")

Arguments

ts

Data frame with time series as created inside function g.part5

ID

Recording identifier (character or numeric)

epochlength

Numeric to indicate epoch length in seconds in the ts object

logs_diaries

Object produced by g.loadlog function

desiredtz

See g.getmeta

Value

Dataframe with one row per sustained inactivity bout and corresponding properties stored in the data.frame columns.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Detects whether accelerometer is worn

Description

Uses the object produced by g.part1 to assess whether the accelerometer was worn

Usage

  g.weardec(metalong, wearthreshold, ws2, params_cleaning = NULL,
            desiredtz = "", qwindowImp = c())

Arguments

metalong

Object produced by g.getmeta

wearthreshold

Number of axis that at least need to meet the non-wear criteria

ws2

Large windowsize used in seconds to apply non-wear detection Small window size not needed, because this is inherent to the object M

params_cleaning

Parameters object with cleaning paramete, see GGIR.

desiredtz

See GGIR

qwindowImp

See g.impute

Value

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  data(data.getmeta)
  params_cleaning = load_params()$params_cleaning
  params_cleaning[["nonwearFilterWindow"]] = c(22, 7)
  output = g.weardec(metalong = data.getmeta$metalong, wearthreshold = 2, ws2 = 900,  
                      params_cleaning = params_cleaning,
                      desiredtz = "", qwindowImp = NULL)

Get basic info form the part 1 milestone file

Description

Internal function to get basic info form the part 1 milestone file

Usage

  getPart1BasicInfo(fn, idloc, tz)

Arguments

fn

Character with full file path to RData file as stored by g.part1

idloc

See GGIR

tz

As passed by GGIR and equal to parameter desiredtz as documented in GGIR

Value

Data.frame with ID, start and end time of the recording, filename and brand name.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


get split names from filename

Description

Internal function to get split names from filename if recording was split.

Usage

   getSplitNames(filename)

Arguments

filename

Character of filename

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Set monitor brand specific parameters

Description

Set monitor brand specific thresholds for non-wear detection, clipping etection, and blocksizes to be loaded. Not designed for direct use by user.

Usage

  get_nw_clip_block_params(monc, dformat, deviceSerialNumber = "", sf,
                            params_rawdata)

Arguments

monc

See g.inspectfile

dformat

See g.dotorcomma

deviceSerialNumber

As produced by g.extractheadervars

sf

Numeric, sample frequency in Hertz

params_rawdata

See GGIR

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Get starttime (adjusted), weekday, and adjust data accordingly.

Description

Function not intended for direct use by user. Used inside g.getmeta as an intermediate step between loading the raw data and calibrating it. This step includes extracting the starttime and adjusting it to nearest integer number of long epoch window lengths in an hour, truncating the data accordingly, and extracting the corresponding weekday.

Usage

  get_starttime_weekday_truncdata(monc, 
  dformat, data, header, desiredtz, sf,
  datafile, ws2, configtz = NULL)

Arguments

monc

See g.inspectfile

dformat

See g.dotorcomma

data

Data part of g.readaccfile output

header

Header part of g.readaccfile output

desiredtz

See g.getmeta

sf

Numeric, sample frequency in Hertz

datafile

See g.getmeta

ws2

Long epoch length

configtz

See g.getmeta

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Extracts folderstructure based on data directory.

Description

Extracts folderstructure based on data directory. This is used when accelerometer files are stored in a hierarchical folder structure and the user likes to have a reference to the exact position in the folder tree, rather than just the filename. Function not intended for direct use by package user.

Usage

getfolderstructure(datadir=c(),referencefnames=c())	

Arguments

datadir

Argument datadir as used in various other functions in GGIR

referencefnames

vector with filename to filter on

Value

List with items:

Examples

  ## Not run: 
    folderstructure = getfolderstructure(datadir)
  
## End(Not run)

Identifies levels of behaviour for g.part5 function.

Description

Identifies levels of behaviour from acceleratioon and sustained inactivity sibdetection (using angles). Function not intended for direct use by package user.

Usage

  identify_levels(ts, TRLi,TRMi,TRVi,
                  ws3, params_phyact, ...)

Arguments

ts

Data.frame with time series genrated in .gpart5

TRLi

Numeric acceleration threshold light

TRMi

Numeric acceleration threshold moderate

TRVi

Numeric acceleration threshold vigorous

ws3

Numeric size of epoch in seconds

params_phyact

See g.part2

...

Any argument used in the previous version of identify_level, which will now be used to overrule the arguments specified with the parameter objects.

Value

List with items:

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples

  ## Not run: 
    levels = identify_levels(TRLi,TRMi,TRVi,
                               boutdur.mvpa,boutcriter.mvpa,
                               boutdur.lig,boutcriter.lig,
                               boutdur.in,boutcriter.in,
                               ws3,bout.metric)
  
## End(Not run)

Identify the Device Brand from a Binary File

Description

This function identifies the brand of a device (e.g., GENEActiv or MATRIX) based on the contents of a binary file. If the file is unrecognized, it returns a default value indicating the device is not recognized.

Usage

inspect_binFile_brand(filename)

Arguments

filename

The path to the binary file to be inspected.

Details

The function performs the following steps:

  1. Reads the file header to check for the presence of a "Device Type" field.

  2. If the device type contains the string "GENEActiv", the device is identified as a GENEActiv device.

  3. If the "Device Type" field is not found, it checks for a MATRIX device by validating a specific header value ("MDTC").

  4. If neither device type is detected, the function returns "not_recognised".

Value

A character string representing the detected device brand:

Author(s)

Jairo H Migueles <jairo@jhmigueles.com>


Check whether character timestamp is in iso8601 format.

Description

Checks whether timestamp stored in character format is in ISO8601 format or not

Usage

is.ISO8601(x)	

Arguments

x

Timestamps in character format either in ISO8601 or as "yyyy-mm-dd hh:mm:ss".

Examples

x ="1980-1-1 18:00:00"
is.ISO8601(x)

Check whether the night starting on a calendar date has DST.

Description

Tests whether the night that follows the input calendar date is a night with day saving time (DST) and on what hour the time moved.

Usage

  is_this_a_dst_night(calendar_date=c(),tz="Europe/London")

Arguments

calendar_date

Character in the format dd/mm/yyyy

tz

Time zone in "Europe/London" format.

Value

dst_night_or_not

If value=0 no DST, if value=1 time moved forward, if value=-1 time moved forward

dsthour

Either the double hour or the hour that was skipped, this differs between countries

Examples

  test4dst = is_this_a_dst_night("23/03/2014",tz="Europe/London")

Checks whether datadir is a directory or a vector with filenames

Description

Checks whether argument datadir used in various other functions in GGIR is the name of a directory that includes data files or whether it is a vector with the full paths to one or more data files

Usage

isfilelist(datadir)	

Arguments

datadir

Argument datadir as used in various other functions in GGIR

Value

Boolean whether it is a list of files (TRUE) or not (FALSE)

Examples

## Not run: 
isitafilelist = isfilelist(datadir)

## End(Not run)

Checks whether the files to process are collected with movisens accelerometers.

Description

Checks whether the files in the datadir folder are files collected with movisens accelerometers. Note that movisens data are stored in one folder per recording that includes multiple bin-files (instead of one file per recording as usual in other accelerometer brands). Therefore, datadir indicates the directory where all the recording folders are stored, then, GGIR reads the pertinent bin files from every folder.

Usage

  ismovisens(data)	

Arguments

data

Full path to the recording folder (with the bin files inside) or the datadir (where all the recording folders are stored).

Value

Boolean whether it is a movisens file (TRUE) or not (FALSE)

Examples

  ## Not run: 
    is.mv = ismovisens(data)
  
## End(Not run)

Convert iso8601 timestamps to POSIX timestamp

Description

To avoid ambiguities when sharing and comparing timestamps. All timestamps are expressed in iso8601 format: https://en.wikipedia.org/wiki/ISO_8601 However, to generate plots in R we need to convert them back to POSIX

Usage

iso8601chartime2POSIX(x,tz)

Arguments

x

Vector of timestamps in iso8601 in character format

tz

Timezone of data collection, e.g. "Europe/London". See List_of_tz_database_time_zones on Wikipedia for full list.

Examples

x ="2017-05-07T13:00:00+0200"
tz = "Europe/Amsterdam"
x_converted = iso8601chartime2POSIX(x,tz)

Load default parameters

Description

Loads default paramter values Not intended for direct use by GGIR users.

Usage

  load_params(topic = c("sleep", "metrics", "rawdata", "247",
                        "phyact", "cleaning", "output", "general"))

Arguments

topic

Character vector with parameter groups to be loaded.

Value

Lists of parameter objects

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Improve the labelling of rest with marker button data

Description

Improve the labelling of rest with marker button data. Currently only functional for Actiwatch and Philips Healthband.

Usage

  markerButtonForRest(sibreport, params_sleep, ts)

Arguments

sibreport

sibreport data.frame produced by g.sibreport

params_sleep

See GGIR

ts

Data.frame with time series object passed on from g.part5_analyseSegment and g.part5.

Value

Updated sibreport

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Builds Section for Parameters Vignette

Description

Function extracts the documentation for a given GGIR argument as provided in the GGIR documentation and builds the structure for the Parameters Vignette. Function not designed for direct use by package user.

Usage

  parametersVignette(params = "sleep")

Arguments

params

Character (default = "sleep"). Name of the parameters object to build its corresponding section in the Parameters vignette.

Value

Structure for the vignette subsection.

Author(s)

Jairo Hidalgo Migueles <jairo.hidalgo.migueles@gmail.com>


part6AlignIndividuals

Description

Align individual time series per household where households are identified by the character or number string between the first and second '-' in the filename.

Usage

  part6AlignIndividuals(GGIR_ts_dir = NULL, outputdir = NULL,
                      path_ggirms = NULL, desiredtz = "", verbose = TRUE)

Arguments

GGIR_ts_dir

Character, path to time series directory in the GGIR output

outputdir

Directory where you would like to store the output

path_ggirms

path to GGIR created folder named meta, with the milestone data files

desiredtz

Character, specifying the timezone database name of the timezone the data was collected in.

verbose

See details in GGIR.

Value

no object is returned, only files are created in the output directory


part6PairwiseAggregation

Description

Pairwise aggregation of the time series of a group.

Usage

  part6PairwiseAggregation(outputdir = NULL, desiredtz = "", verbose = TRUE)

Arguments

outputdir

Directory where you would like to store your results

desiredtz

Character, specifying the timezone database name of the timezone the data was collected in

verbose

See details in GGIR.

Value

No object is returned, only files are created in the output directory


Read custom csv files with accelerometer data

Description

Loads csv files with accelerometer data and standardises the output format (incl. unit of measurement, timestamp format, header format, and column locations) to make the data compatible with other GGIR functions.

Usage

  read.myacc.csv(rmc.file=c(), rmc.nrow=Inf, rmc.skip = c(), rmc.dec=".",
                          rmc.firstrow.acc = c(), rmc.firstrow.header=c(),
                          rmc.header.length = c(),
                          rmc.col.acc = 1:3, rmc.col.temp = c(), 
                          rmc.col.time=c(),
                          rmc.unit.acc = "g", rmc.unit.temp = "C", 
                          rmc.unit.time = "POSIX",
                          rmc.format.time = "%Y-%m-%d %H:%M:%OS",
                          rmc.bitrate = c(), rmc.dynamic_range = c(), 
                          rmc.unsignedbit = TRUE,
                          rmc.origin = "1970-01-01",
                          rmc.desiredtz = NULL,
                          rmc.configtz = NULL,
                          rmc.sf = c(),
                          rmc.headername.sf = c(),
                          rmc.headername.sn = c(),
                          rmc.headername.recordingid = c(),
                          rmc.header.structure = c(),
                          rmc.check4timegaps = FALSE,
                          rmc.col.wear = c(),
                          rmc.doresample = FALSE,
                          rmc.scalefactor.acc = 1,
                          interpolationType=1, 
                          PreviousLastValue = c(0, 0, 1),
                          PreviousLastTime = NULL,
                          desiredtz = NULL,
                          configtz = NULL,
                          header = NULL)	

Arguments

rmc.file

Filename of file to be read if it is in the working directory, or full path to the file otherwise.

rmc.nrow

Number of rows to read, same as nrow argument in read.csv and nrows in fread. The whole file is read by default (i.e., rmc.nrow = Inf).

rmc.skip

Number of rows to skip, same as skip argument in read.csv and in fread.

rmc.dec

Decimal used for numbers, same as skip argument in read.csv and in fread.

rmc.firstrow.acc

First row (number) of the acceleration data.

rmc.firstrow.header

First row (number) of the header. Leave blank if the file does not have a header.

rmc.header.length

If file has header, specify header length (numeric).

rmc.col.acc

Vector with three column (numbers) in which the acceleration signals are stored

rmc.col.temp

Scalar with column (number) in which the temperature is stored. Leave in default setting if no temperature is avaible. The temperature will be used by g.calibrate.

rmc.col.time

Scalar with column (number) in which the timestamps are stored. Leave in default setting if timestamps are not stored.

rmc.unit.acc

Character with unit of acceleration values: "g", "mg", or "bit"

rmc.unit.temp

Character with unit of temperature values: (K)elvin, (C)elsius, or (F)ahrenheit

rmc.unit.time

Character with unit of timestamps: "POSIX", "UNIXsec" (seconds since origin, see argument rmc.origin), "character", or "ActivPAL" (exotic timestamp format only used in the ActivPAL activity monitor).

rmc.format.time

Character string giving a date-time format as used by strptime. Only used for rmc.unit.time: character and POSIX.

rmc.bitrate

Numeric: If unit of acceleration is a bit then provide bit rate, e.g. 12 bit.

rmc.dynamic_range

Numeric, if unit of acceleration is a bit then provide dynamic range deviation in g from zero, e.g. +/-6g would mean this argument needs to be 6. If you give this argument a character value the code will search the file header for elements with a name equal to the character value and use the corresponding numeric value next to it as dynamic range.

rmc.unsignedbit

Boolean, if unsignedbit = TRUE means that bits are only positive numbers. if unsignedbit = FALSE then bits are both positive and negative.

rmc.origin

Origin of time when unit of time is UNIXsec, e.g. 1970-1-1

rmc.desiredtz

Deprecated, please see desiredtz.

rmc.configtz

Deprecated, please see configtz.

rmc.sf

Sample rate in Hertz, if this is stored in the file header then that will be used instead.

rmc.headername.sf

If file has a header: Row name (character) under which the sample frequency can be found.

rmc.headername.sn

If file has a header: Row name (character) under which the serial number can be found.

rmc.headername.recordingid

If file has a header: Row name (character) under which the recording ID can be found.

rmc.header.structure

Character used to split the header name from the header value, e.g. ":" or " "

rmc.check4timegaps

Boolean to indicate whether gaps in time should be imputed with zeros. Some sensing equipment provides accelerometer with gaps in time. The rest of GGIR is not designed for this, by setting this argument to TRUE the the gaps in time will be filled with zeros.

rmc.col.wear

If external wear detection outcome is stored as part of the data then this can be used by GGIR. This argument specifies the column in which the wear detection (Boolean) is stored.

rmc.doresample

Boolean to indicate whether to resample the data based on the available timestamps and extracted sample rate from the file header

rmc.scalefactor.acc

Numeric value (default 1) to scale the acceleration signals via multiplication. For example, if data is provided in m/s2 then by setting this to 1/9.81 we would derive gravitational units.

interpolationType

Integer to indicate type of interpolation to be used when resampling time series (mainly relevant for Axivity sensors), 1=linear, 2=nearest neighbour.

PreviousLastValue

Automatically identified last value in previous chunk of data read.

PreviousLastTime

Automatically identified last timestamp in previous chunk of data read.

desiredtz

Timezone in which device was worn.

configtz

Timezone in which device was configured. If equal to desiredtz you can leave this in its default value.

header

Header information that was extracted the previous time this file was read, to be re-used instead of being extracted again.

Details

To use this function in the context of GGIR use all arguments from this function, except rmc.file, rmc.nrow, and rmc.skip as input for function GGIR or g.part1 and also specify argument rmc.noise, which is not part of this function but needed to tell GGIR what noise level to expect in the data. The rmc.noise is taken from the params_rawdata object if not explicitly specified by user.

Value

List with objects data holding the time series of acceleration with among others a column named "time" that holds the time expressed in seconds since 1-1-1970, and header if a header was present in the input file.

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

Examples


  # create test files: No header, with temperature, with time
  N = 30
  sf = 30
  x = Sys.time()+((0:(N-1))/sf)
  timestamps = as.POSIXlt(x, origin="1970-1-1", tz = "Europe/London")
  mydata = data.frame(x = rnorm(N), time = timestamps, y = rnorm(N), z = rnorm(N),
            temp = rnorm(N) + 20)
  testfile = "testcsv1.csv"
  write.csv(mydata, file= testfile, row.names = FALSE)
  loadedData = read.myacc.csv(rmc.file=testfile, rmc.nrow=20, rmc.dec=".",
                      rmc.firstrow.acc = 1, rmc.firstrow.header=c(),
                      desiredtz = "",
                      rmc.col.acc = c(1,3,4), rmc.col.temp = 5, rmc.col.time=2,
                      rmc.unit.acc = "g", rmc.unit.temp = "C", rmc.origin = "1970-01-01")
  if (file.exists(testfile)) file.remove(testfile)
  

Append GGIR milestone data from neighbouring or overlapping recordings

Description

Splits GGIR part 1 milestone data format files based on params_general parameters recording_split_times, recording_split_timeformat, and recording_split_times.

Usage

   splitRecords(metadatadir, params_general = NULL)

Arguments

metadatadir

See g.part2

params_general

See GGIR

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>


Round numeric columns and replace NA/NaN values by blank

Description

Identifies columns that can be coerced to numeric in a data frame, transforms these columns to numeric and round them to the specified digits. It also replaces NA and NaNs values by blank.

Usage

  tidyup_df(df = c(), digits = 3)

Arguments

df

Data frame

digits

Integer indicating the number of decimal places (round) or significant digits (signif) to be used

Value

Data frame with all possible columns as numeric and rounded to the specified number of digits

Author(s)

Jairo H Migueles

Examples

  # Test data frame
  df = data.frame(a = c("a", "b"), b = as.character(c(1.543218, 8.216856483)))
  tidyup_df(df = df, digits = 3)

Update blocksize of data to be read depending on available memory.

Description

Function queries available memory to either lower or increase the blocksize used by function g.readaccfile

Usage

updateBlocksize(blocksize, bsc_qc)

Arguments

blocksize

Number of filepages (binary data) or rows (other dataformats).

bsc_qc

Data.frame with columns time (timestamp from Sys.time) and size (memory size). This is used for housekeeping in g.calibrate and g.getmeta

Value

List with blocksize and bsc_qc, same format as input, although bsc_qc has one new row.


Generate visualisation of time series produced by part 5.

Description

Function called by GGIR. Not intended for direct use by user

Usage

  visualReport(metadatadir = c(), 
              f0 = c(), f1 = c(), overwrite = FALSE,
              desiredtz = "",
              verbose = TRUE,
              part6_threshold_combi = NULL, GGIRversion = NULL,
              params_sleep = NULL,
              params_output = NULL)

Arguments

metadatadir

Directory that holds a folder 'meta' and inside this a folder 'basic' which contains the milestone data produced by g.part1. The folderstructure is normally created by g.part1 and GGIR will recognise what the value of metadatadir is.

f0

File index to start with (default = 1). Index refers to the filenames sorted in alphabetical order

f1

File index to finish with (defaults to number of files available, i.e., f1 = 0)

overwrite

See GGIR

desiredtz

See GGIR

verbose

See GGIR

part6_threshold_combi

See GGIR

GGIRversion

Character with GGIR version number

params_sleep

See GGIR

params_output

See GGIR

Value

No values, this function only generates a plot

Author(s)

Vincent T van Hees <v.vanhees@accelting.com>

mirror server hosted at Truenetwork, Russian Federation.