> 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/respiration/r-notebooks-respiration-respiration-processing.md).

# R Notebooks (Respiration): Respiration Processing

Run the Respiration Processing R notebook to compute respiration rate, cycle count and cycle, inhalation and exhalation durations, with markers for each phase.

*The Respiration Processing R Notebook computes the respiration cycle count, the respiration rate, the average duration of respiratory cycles and from iMotions v10.5 also the average duration of inhalation and exhalation phases as well as automated markers for those respiratory phases. The respiration measurements can provide information about our cognitive, emotional, and physiological states. Learn more about respiration from* [*here*](https://imotions.com/blog/learning/best-practice/respiration-research/)*.*

## Prerequisites

Supported sensors: Biopac (RSP100C), Biopac Bionomadix, RespiBAN BLE, and Plux Respiration

## How to Analyze in iMotions Desktop

1\. Create a new analysis for the study that you wish to run the R-Notebook for:

![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" and "Segmentation Criteria", with your preferred selections, until you reach the step named "Signal processing".

3\. By clicking "+" next to "Active flows" you can select the algorithms you want to use for signal processing. Select the Respiration sensor (for example "Biopac RSP 100C") for which you want to apply the respiration R Notebook in the drop-down "Device" menu. Select the algorithms in the drop-down “Algorithm” menu.

![](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)

4\. You can name the analysis in the "Flow name" menu. Alter the parameters to suit your research needs, then click on “Next”. The parameters will be described in detail in the next section of this article: [Algorithm Introduction](https://help.imotions.com/lab/analysis/respiration/r-notebooks-respiration-respiration-processing.md).

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

5\. Select the stimulus you wish to be included in the analysis. Then click the "Add" button to add the analysis and close the dialog.

![aanlysis.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-1f16d728378791a161ac0e361e0ab2a6dd3a25aa%2F7d4c5727d1_aanlysis-3-.webp?alt=media)

## Algorithm Introduction

1\. Data Retrieval: The raw respiration signal from the sensor is retrieved for a given respondent (expressed in volts, V).

2\. Data Interpolation: Possible gaps in the signal due to signal drops are identified and linearly interpolated, if the gap is no longer than 4000 ms. Else, each fragment of signal is analyzed separately.

3\. Bandpass Filtering: A second-order, zero-phase-lag bandpass butterworth filter is applied. The high-pass and low-pass parameters are determined as follows:

The high-pass cutoff is set to 0.05 Hz in order to detrend the signal.

The low-pass cutoff is set 1 Hz below the Nyquist frequency, which is half the sampling rate:

If sampling rate is 200 Hz, low-pass cutoff is 99 Hz

If sampling rate is 100 Hz, low-pass cutoff is 49 Hz

4\. Noise Removal: A second-order zero-phase-lag bandstop butterworth filter is applied to remove line noise from the surrounding environment. This step is optional. To check if your country operates at 50 Hz or 60 Hz, search for “Your Country Name + 50 Hz or 60 Hz” on any search engine. Countries like the USA, Canada, Mexico, Guatemala, some African, and Asian countries use 60 Hz. Everywhere else typically uses 50 Hz. This search will help you know if you need a 50 Hz or 60 Hz filter.

5\. Scaling: The filtered signal is scaled using the following formula: scaled\_data=(x−mean(x))sd(x)

6\. Phases: Onsets and offsets for inhalations/exhalations phases are detected on the scaled signal. Onsets are all the points where the scaled signal crosses above 0 (inhalation) or below 0 (exhalation). Offsets are the points where the scaled signal crosses below 0 (inhalation) or above 0 (exhalation). To deal with the scaled signal fluctuating around 0, phases separated by a time duration inferior to 500 ms are merged together. This merging is performed first on inhalations phases (removing short exhalations) and then on exhalations phases (removing short inhalations).

7\. Cycle and phases metrics: Respiration cycles are determined based on the identified phases. Only cycles consisting of a whole inhalation phase succeeded by a whole exhalation phase are retained for the computation of metrics; any incomplete cycles are excluded. The number of respiration cycles, the respiration rate (cycles/min), and the average duration of a respiration cycle (s) are then calculated for each stimulus. The respiration rate is obtained by dividing the total number of cycles by the sum of their duration, multiplied by 60. The average duration of inhalation (s) and average duration of exhalation (s) of these complete cycles are also computed. In the export, it is possible to include whole inhalation/exhalation phases detected during truncated respiration cycles.

8\. Respiration rate: A respiration rate signal, denoted in cycles per minute (cycles/min), is produced. The signal is dynamically updated for each identified cycle using the formula: respiration\_rate=60cycle\_duration, where “cycle\_duration” represents the time elapsed between the onset of an inhalation phase and the offset of the subsequent exhalation phase. This dynamically updated respiration rate signal can be found in the individual replay, in the SensorData exports as well as Respiration Phase Tables exports (called RSPPhaseTable.csv).

## Outputs

### Desktop replay

In the individual replays of data, you can visualize signals and calculated metrics, and from iMotions v10.5 you can visualize the inhalation and exhalation signals as well as automated inhalation/exhalation markers, displayed as follows:

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

* **Signals**:
  * From iMotions v10.5
    * **Inhalation (binary):** The detected respiration peaks samples where the amplitudes are above a predefined threshold. Detected peak samples are assigned a value of "1". Other samples outside it are assigned a value of "0".
    * **Exhalation (binary):** The detected respiration peaks samples where the amplitudes are below a predefined threshold. Detected peak samples are assigned a value of "1". Other samples outside it are assigned a value of "0".
    * **Respiration rate:** A respiration rate signal, denoted in cycles per minute (cycles/min), is produced. The signal is dynamically updated for each identified cycle using the formula: respiration\_rate=60/cycle\_duration, where “cycle\_duration” represents the time elapsed between the onset of an inhalation phase and the offset of the subsequent exhalation phase.
* **Metrics**:
  * **Respiration cycle count**: Number of cycles within the displayed stimulus and respondent.
  * **Respiration rate \[cycle/min]**: Number of respiration cycles per minute within the displayed stimulus and respondent. The normal resting respiration rate for adults is about 12 to 20 breaths per minute.
  * **Average respiration cycle duration \[sec]**: Average duration (sec) per respiration cycle, for the displayed stimulus and respondent.
  * From iMotions v10.5 also: **Average inhalation duration \[sec]** and **average exhalation duration \[sec]:** Average duration (sec) per respiration phase (inhalation or exhalation), for the displayed stimulus and respondent.

### Exported Files:

From iMotions v10.5, there are three types of files you can export: Sensor Data files, and two types of R processing files: Respiration metrics file (called RSPMetrics.csv) and Respiration phase table file (called RSPPhaseTable.csv). In iMotions v10.4 and older iMotions versions, Respiration phase tables aren't reported.

* **Sensor Data file:** This is the raw sensor data export. It can also include R-processed signals by ticking the "**R analysis Respiration**" in iMotions v10.5 or newer as shown in the screenshot below OR by ticking the "Processed and imported data" in iMotions v10.4 or previous versions.

  ![one\_for\_all.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-948a8dc64336719a9e8e14e1c83195c82f4f50cb%2F8da7021855_one_for_all-7-.webp?alt=media)

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

The SensorData file can have the following layout:

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

* **Respiration metrics file:** This file includes the processed results from R Notebooks across respondents and stimuli. You can access the exported file by (1) clicking on the 'Export' button, (2) under 'R PROCESSING', you can (3) select to have Individual metrics exports (to obtain a separate export file per modality) or a Single multi-modal export (relevant when you use more than one modality), you can click on (4) 'Respiration Metrics Export'. Here, when you click the drop down menu, you can visualize further options as illustrated as follows:

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

As clarification: As a result of choosing the "**include whole inhalation/exhalation phases detected during truncated respiration cycles**" option shown in the screenshot above, the Respiration analysis will calculate the average duration of inhalation and exhalation metrics including the inhalation and exhalations that happen to be part of *truncated or incomplete* respiration cycles. If you don't choose this option, the average duration of inhalation and exhalation will be calculated excluding such inhalations/exhalations (which are part of *truncated or incomplete* respiration cycles).

When you finally (5) click the blue Export button, you will export the Respiration metrics file (RSPMetrics.csv), which has the following layout:

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

### Descriptions on the Respiration metrics file:

This file is called RSPMetrics file and is exported in .csv format. The file has one row for each respondent and each **stimulus**/**scene**/**scene fragment**/**annotation**/**annotation instance** within the study. Each row contains information about detected respiration cycle metrics and inhalation/exhalation average duration for this respondent during that stimulus/scene/scene fragment/annotation/annotation instance.

| **Header**                                                                   | **Explanation**                                                                                                                                  |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Study Name                                                                   | The name of the study                                                                                                                            |
| Respondent Name                                                              | The respondent under a certain stimulus type                                                                                                     |
| Gender                                                                       | The gender of the respondent under a certain stimulus type                                                                                       |
| Age                                                                          | The age of the respondent under a certain stimulus type                                                                                          |
| Group                                                                        | The group variables of the respondent you specified when creating the study                                                                      |
| Type                                                                         | Type of the stimulus during which these respiration peaks were experienced: Stimulus, Scene, Scene (Fragment), Annotation, Annotation (Instance) |
| Label                                                                        | The given name of the stimulus, scene, and annotation                                                                                            |
| Start (ms)                                                                   | The start time (in ms) of the certain stimulus type relative to the start of the study                                                           |
| Duration (ms)                                                                | The duration (in ms) of the certain stimulus type                                                                                                |
| Parent Stimulus                                                              | The name of the stimulus where the scene was created from; the name of the stimulus/scene where the annotation was created from                  |
| Respiration cycle count                                                      | The number of detected breaths the respondent had during the certain stimulus type                                                               |
| Respiration rate \[cycle/min]                                                | Breath rate by minute the respondent had during the certain stimulus type                                                                        |
| Average respiration cycle duration \[sec]                                    | The average respiration cycle time the respondent had during the certain stimulus type                                                           |
| <p>Average inhalation duration \[sec]<br>(from iMotions v10.5 and newer)</p> | The average duration of the inhalation phase the respondent had during the certain stimulus type                                                 |
| <p>Average exhalation duration \[sec]<br>(from iMotions v10.5 and newer)</p> | The average duration of the exhalation phase the respondent had during the certain stimulus type                                                 |

* **Respiratory Phase Table** (called RSPPhaseTable.csv)

The Respiratory Phase Table describes the index number, the onset, offset and duration of each Respiratory phase (i.e. Inhalation and Exhalation) per respondent and per stimulus/scene/scene fragment/annotation/annotation instance. In these exports, you will find a column called Truncation type that will describe whether the identified Inhalation/Exhalation is truncated (incomplete for the given stimulus/scene/annotation) or whole (complete).

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

**Reports**

When you click the **Reports** button (as shown below), you can access the entire description of the signal processing steps done starting from the raw unprocessed respiration signal.

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

An example of a Respiration report is shown as follows:

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-5461b2258812637c6bf3d78eda5c8e314db3c0d7%2F66eace508d_Slide6-1-.webp?alt=media) ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-8b2b1182310ff1869048f8f98874f46cb10081eb%2Fcea82ba6a9_Slide8-1-.webp?alt=media)


---

# 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/respiration/r-notebooks-respiration-respiration-processing.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.
