> For the complete documentation index, see [llms.txt](https://help.imotions.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.imotions.com/lab/analysis/signal-processing-r-notebooks/r-notebook-epoching.md).

# R Notebook Epoching

Run the epoching R notebooks to split GSR, heart rate and EMG signals into time epochs per stimulus and export them for statistics such as analysis of variance.

In the field of communication science (e.g. media industry or neuromarketing), the interest often arises for a moment-to-moment representation of the physiological data towards a stimulus. These R Notebooks prepare the GSR, ECG, EMG time series data for further statistical methods (e. g. analysis of variance) through a process of dimensionality reduction (downsampling). This simplified representation is also better for visualizations in publications.

The R Notebooks concerned are called **GSR Epoching Pre-processing**, **Heart Rate and Heart Rate Variability**, **EMG Processing** (added in the active flow when adding signal processing algorithms, responsible for GSR, ECG, EMG signal pre-processing) and **Epoch Export** (later in the export panel, responsible for epoching and export)**.**

## 1. Prerequisites

Supported stimulus types: All

Supported sensors: Shimmer, Biopac, Empatica E4 (EDA/GSR). Polar Belt is not supported for this notebook yet.

## 2. How to Analyze in iMotions Desktop

#### The following steps need to be followed:

1. Create a new analysis for the study for which you wish to run the R Notebook.

   ![The Add Analysis button on a study in the Library](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-0b352d688758cd75a0a20712355835132fb525d1%2Flab_library_add-analysis-button.png?alt=media)
2. Advance through the steps "Segmentation settings" with your preferred selections and "Segmentation criteria" until you reach the step "Signal processing".

   ![22.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-64e970cd42490f0b1fd7302a162f3a77b90adc0f%2Fb729e619ef_22-1-.webp?alt=media)
3. By clicking "+" next to "Active flows", you can select the algorithms you want to use for signal processing (Label **1**). Select the sensor for which you want to apply the R Notebook in the drop-down "Devices" menu (Label **2**). In the drop-down “Algorithm” menu (Label **3**), select the "**GSR Epoching Pre-processing**" algorithm if you want to apply epoching on GSR signal; "**Heart Rate and Heart Rate Variability**" algorithm, if you want to apply epoching on ECG Heart Rate, computed from ECG signal, "**EMG Processing**" if you want to apply epoching on EMG signal. Name the analysis in the "Flow name" menu (Label **4**). Alter the parameters to suit your research needs (Label **5**), then click on “Next” (Label **6**). The parameters will be described in detail in the next section of this article: Epoching Algorithm. ***Note:*** *it is possible (from version 8.1 and onwards), to run the notebook on multiple sensors of the same kind. E.g., you can run the notebook on the second Shimmer device here by giving a unique device name and adding an additional Active flow with the device you would like to analyze on.* ***Note:** that R Notebooks you have added so far are only responsible for GSR, ECG, EMG signal pre-processing, to prepare them for further epoching and export.*

   ![analysis\_creation\_shimmer2.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-229f7d60dff16cb71155658e6709c27fd2cdf71b%2F2146140451_analysis_creation_shimmer2.webp?alt=media)
4. Select the stimuli to be included in the analysis. Then click the "Add" button to add the analysis and close the dialog. ***Note:** The Epoching R Notebook is **not** applicable for scenes created with **multiple (two or more than two)** fragments.*

   ![Add\_stimulus.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-9f832540b338e69bb1f540adbb033b83fb67eaac%2F56b681fa40_add_stimulus.webp?alt=media)
5. You can do epoching and access the exported file by (1) clicking on the 'Export' orange button, (2) click 'R PROCESSING' tab, (3) click on 'Epoch Export', and then (4) alter the parameters **\[Method for epoching]** to choose which method you want to use for epoching, there are two options: **Fixed duration** or **Fixed number of epochs**. Type in the **\[Time epoch length \[ms], for Method: Fixed duration]** or **\[Time epoch number, for Method: Fixed number of epochs]** according to the epoching method you choose. And finally (5) click on the 'Export individual files' green button to generate the file. You can also choose to export epoched GSR, ECG Heart Rate, and smoothed EMG into one file (if these signals are available in your study).

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-8d4f9e812ef324a60bcb1f45a7a0dfdfa9348973%2F8923c091d6_image-1672335605390.webp?alt=media)

## 3. Epoching Algorithm

**Pre-processing:**

**A. GSR Epoching Pre-processing:**

The calibrated GSR signal from the sensor is retrieved for the given stimulus and respondent (expressed in microSiemens, µS).

**Shimmer sensor only:** parameter **\[Shimmer GSR channel for applying epoching]** is used to pick which GSR signal you want to apply epoching on. Two options: **GSR Conductance CAL** or **GSR Resistance CAL**. Parameter **\[Gap interpolation length threshold \[ms]]** is used to identify possible gaps in the signal due to signal drops. If a gap in the signal is shorter than this threshold, then the missing data is linearly interpolated. Otherwise, the gap is left and each of the signal fragments is processed separately.

A low-pass [Butterworth filter](https://en.wikipedia.org/wiki/Butterworth_filter) with cutoff frequency: parameter **\[Lowpass filter cutoff frequency \[Hz]]** is applied to the GSR signal (in order to remove powerline noise).

***Optional***: If the checkbox **\[Apply a moving median filter]** is checked, a running median filter of a fixed-length window: **\[Moving median filter length \[ms]]** will be applied to the low-passed GSR signal, to remove rapid-transient artifacts. The default value is 500 milliseconds. The method is described in paper ([Gautam et al. 2018](#references)).

***Note**: An example of how to relate time window length with sample number: With a sampling rate of 128HZ, a 500 milliseconds window corresponds to 128 (sampling rate) \* 0.5 second (time window length) = 64 sample number.*

**B. Heart Rate and Heart Rate Variability:**

Please [see this article](https://help.imotions.com/lab/analysis/biosensor-analysis/r-notebooks-ecg-heart-rate-and-hrv-processing.md) for a detailed description of how Heart Rate signal is computed from raw ECG signal.

**C. EMG Processing:**

Please [see this article](https://help.imotions.com/lab/analysis/biosensor-analysis/r-notebook-emg-processing.md) for a detailed description of how smoothed EMG signal is computed from raw EMG signal.

**Epoching and Exporting:**

During the export phase, the pre-processed signal (GSR, Heart Rate, or smoothed EMG) is epoched based on two methods - **Fixed duration** or **Fixed number of epochs**.

***Fixed duration:*** This method reduces the signal of original sampling rate (e.g. 128Hz) to a signal consisting of a number of equally sized time-epochs representing an average information of the signal for that stimulus across time. An epoch size of 1 second is the default value since it seems to be the most popular choice. You have the option to change this value by changing parameter: **\[Time epoch length \[ms], for Method: Fixed duration].**

E.g. The epoch size is set to 1 second: Epoch 1 is the average conditioned signal in the interval \[0 ms; 1000 ms] Epoch 2 is the average conditioned signal in the interval \[1000 ms; 2000 ms] Epoch 3 is the average conditioned signal in the interval \[2000 ms; 3000 ms]. A sample exactly on the boundary between two epochs is included in both.

***Fixed number of epochs:*** Having the same number of epochs for two stimuli of different duration can be helpful when being fed into a statistical analysis. This method will segment the signals into an equal number of epochs and calculate the average information from each epoch. Please note that this method can result in different duration of epoch for different stimuli. You have the option to change the number of epochs you want to have by changing the parameter: **\[Time epoch number, for Method: Fixed number of epochs].**

***Note:** Specified number of epochs should be an integer and larger than 1.* E.g. if the signal for stimulus A is 10 seconds long and for stimulus B is 15 seconds long. The number of epochs is set to 10 Stimulus A Epoch duration = 10 seconds/10 epochs = 1000 ms. Epoch 1 is the average conditioned signal in the interval \[0 ms; 1000 ms] Epoch 2 is the average conditioned signal in the interval \[1000 ms; 2000 ms] Epoch 3 is the average conditioned signal in the interval \[2000 ms; 3000 ms] ... Stimulus B Epoch duration = 15 seconds/10 epochs = 1500 ms Epoch 1 is the average conditioned signal in the interval \[0 ms; 1500 ms] Epoch 2 is the average conditioned signal in the interval \[1500 ms; 3000 ms] Epoch 3 is the average conditioned signal in the interval \[3000 ms; 4500 ms] ...

## 4. The Outputs

### (1) Desktop replay:

Pre-processed (gap-filled (optional), lowpass filtered, median filtered (optional)) selected GSR signal, ready for epoching and export.

![replayed\_preprocessed\_GSR.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-5dbe3e67ea83aa121041c73e819a6983ad09c8af%2F0b7239409b_replayed_preprocessed_gsr.webp?alt=media)

Heart Rate signal computed from raw ECG **ready for epoching and export:**

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-d27d2b3adad0ef8c94aeaa8d40a405e12e74849c%2F2a8140b4cc_image-1672337293145.webp?alt=media)

Smoothed EMG signal computed from raw EMG **ready for epoching and export:**

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-a7fdd79a455767b87abed8ded4740d1eab14dafe%2Fff1ba60559_image-1672337032852.webp?alt=media)

### (2) Exported file

**Each row** of the exported file represents information of **one epoch** for each (respondent, stimulus, sensor) pair. All respondents and stimuli under one created analysis are exported into **one** file. The exported files can be further imported into SPSS Statistics software for more analysis.

![export\_files.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-e77f0be573c0617d840346f5935be53ed83cdb88%2F62a343a95b_export_files.png?alt=media)

METADATA (Device & Algorithm & Signal information):

| Device         | <p>Name of the sensor used to collect the data<br></p> |
| -------------- | ------------------------------------------------------ |
| Algorithm Type | "Epoching"                                             |
| Signal Used    | signals used to apply the epoching on                  |

Column Headers:

| **Header**                 | <p><strong>Explanation</strong><br></p>                                                                                                                             |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Study Name                 | <p>The name of the study<br></p>                                                                                                                                    |
| Respondent Name            | The respondent whom this epoch belongs to                                                                                                                           |
| Gender                     | The gender of the respondent whom this epoch belongs to                                                                                                             |
| Age                        | The age of the respondent whom this epoch belongs to                                                                                                                |
| Group                      | The group variables of the respondent you specified when creating the study                                                                                         |
| <p>Type<br></p>            | <p>Type of the stimulus that this epoch belongs to: Stimulus, Scene (<strong>ONE</strong> Fragment only) or Annotation (<strong>ONE</strong> Instance only)<br></p> |
| <p>Label<br></p>           | <p>The given name of the stimulus, scene or annotation<br></p>                                                                                                      |
| <p>Parent Stimulus<br></p> | <p>The name of the stimulus where the scene was created from; the name of the stimulus/scene where the annotation was created from<br></p>                          |

| Epoch               | Epoch count number, restart from 1 for each (respondent, stimulus type, sensor) pair                                                                                                                                                                              |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Epoch Start (ms)    | The start time (in ms) of the epoch relative to the start of the stimulus, scene or annotation                                                                                                                                                                    |
| Epoch End (ms)      | The end time (in ms) of the epoch relative to the start of the stimulus, scene or annotation                                                                                                                                                                      |
| Epoch Duration (ms) | The duration (in ms) of the epoch                                                                                                                                                                                                                                 |
| Mean                | Mean of the GSR signal in this epoch                                                                                                                                                                                                                              |
| Median              | Median of the GSR signal in this epoch                                                                                                                                                                                                                            |
| Max                 | Maximum value of the GSR signal in this epoch                                                                                                                                                                                                                     |
| Min                 | Minimum value of the GSR signal in this epoch                                                                                                                                                                                                                     |
| Std                 | Standard deviation of the GSR signal in this epoch                                                                                                                                                                                                                |
| Quality             | <p>Percentage of presented data across each specified epoch.<br>For example: under the method Fixed duration, the Quality can be less than 100% if the last epoch is incomplete (duration of the actual GSR signal is shorter than specified epoch duration).</p> |

***Note:** For the 'Fixed duration' Epoching Method, the last epoch ends (Epoch End (ms)) where the fixed duration ends, not where the actual signal ends. This can result in low Quality if the actual signal ends before the fixed duration ends.*

## References

A. Gautam, N. Simoes-Capela, G. Schiavone, A. Acharyya, W. de Raedt and C. Van Hoof, "A Data Driven Empirical Iterative Algorithm for GSR Signal Pre-Processing," *2018 26th European Signal Processing Conference (EUSIPCO)*, Rome, 2018, pp. 1162-1166, doi: 10.23919/EUSIPCO.2018.8553191.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.imotions.com/lab/analysis/signal-processing-r-notebooks/r-notebook-epoching.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
