> 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/biosensor-analysis/r-notebooks-ecg-heart-rate-and-hrv-processing.md).

# R Notebooks: ECG Heart rate and HRV Processing

Run the ECG R notebook to detect heartbeats in ECG or PPG data and compute heart rate and HRV metrics such as RMSSD and SDNN per stimulus in iMotions Lab.

The heart rate, which is calculated from Electrocardiography (ECG) or [photoplethysmogram (PPG)](https://imotions.com/blog/measuring-the-heart-how-does-ecg-and-ppg-work/) signal, is coupled with autonomic nervous system activity. It provides a better understanding of physiological arousal and a suitable proxy for examining how we feel. Heart rate variability (HRV) is associated with [emotional regulation, social skills, and cognitive processes.](https://imotions.com/blog/heart-rate-variability-emotions/)

This article describes the peak detection and calculations of Heart Rate (HR) and HRV based on our R-notebook integration.

The R-notebook is called: **Heart Rate and Heart Rate Variability (HRV)**. It computes the single respondent peak detection, calculations of HR and HRV (SDNN and RMSSD) during each stimulus and from iMotions 10.0.4 automated event markers. From iMotions 10.0.10 onwards, frequency HRV metrics are available. Based on analysis of the power of different frequency ranges of the Inter-Beat-Intervals of ECG, frequency HRV metrics give more insight into autonomic regulation: high-frequency (HF) power mainly reflects parasympathetic (vagal) activity, while low-frequency (LF) power and the LF/HF ratio reflect a mix of sympathetic and parasympathetic influences and are not a reliable measure of the balance between them. These metrics can be used to answer a lot of research questions regarding mental workload, drowsiness, alertness detection etc. From iMotions 10.1.18 onwards PPG is added to this analysis. This means that you can do the same calculations as for ECG, however the results will not be as accurate as if you are using a more accurate ECG sensor for peak detection.

***Supported sensors:***

* Shimmer ECG
* Shimmer PPG (from iMotions 11.0.4 onwards)
* Biopac ECG (ECG100C) through MP150 and MP160
* Biopac Bionomadix ECG
* Biopac Bionomadix PPG (from iMotions 11.0.4 onwards)
* [Bluetooth Low Energy (BLE) devices](https://help.imotions.com/lab/sensor-setup/bluetooth-low-energy-ble-devices.md) such as Polar Belt H10
* Biosignal Plux ECG (from iMotions 10.0.7 onwards)
* Biosignal Plux PPG (the [BVP sensor](https://www.pluxbiosignals.com/products/blood-volume-pulse-bvp-sensor?srsltid=AfmBOortx1bOX72ca54NDOJY6DQ_Ki1e-ZmF4RgaYcLMexxQdiQ1Sjgm), from iMotions 10.1.18 onwards)
* ABM B-Alert ECG channel

*Regarding what Bluetooth Low Energy sensors are and how to connect them in iMotions, please refer to* [*this article*](https://help.imotions.com/lab/sensor-setup/bluetooth-low-energy-ble-devices.md)*.*

| **Devices**                                               | **ECG Related Raw Signals You Could Obtain From the Device** | **Metrics/Signals You Could Obtain from the Notebook**                                                                                                                                                                                                                             |
| --------------------------------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Shimmer ECG                                               | ECG, Heart Rate ECG (LL-RA), IBI ECG (LL-RA)                 | Metrics (Percentage of missed peaks (%), Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%)), Signals (R Peaks Occurrences, Heart Rate, Momentary HRV) |
| Biopac ECG100C                                            | ECG                                                          | Metrics (Percentage of missed peaks (%), Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%)), Signals (R Peaks Occurrences, Heart Rate, Momentary HRV) |
| BLE sensors with R-R intervals like Polar Belt H10        | Heart rate, R-R intervals                                    | Metrics (Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%) will be calculated). Signals (Momentary HRV)                                               |
| BLE sensors without R-R intervals like Polar Verity Sense | Heart rate                                                   | Metrics (Average Heart Rate will be calculated)                                                                                                                                                                                                                                    |
| Biosignal Plux ECG                                        | ECG                                                          | Metrics (Percentage of missed peaks (%), Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%)), Signals (R Peaks Occurrences, Heart Rate, Momentary HRV) |
| ABM B-Alert                                               | ECG                                                          | Metrics (Percentage of missed peaks (%), Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%)), Signals (R Peaks Occurrences, Heart Rate, Momentary HRV) |
| PPG sensors                                               | PPG                                                          | Metrics (Percentage of missed peaks (%), Average Heart Rate, Average IBI, SDNN, RMSSD, VLF Power, LF Power, HF Power, LF/HF (%), Normalized LF Power, Normalized HF Power, Relative LF Power (%), Relative HF Power (%)), Signals (R Peaks Occurrences, Heart Rate, Momentary HRV) |

## 1. How to Analyze in iMotions Desktop

As for the **Heart Rate and Heart Rate Variability** R Notebook, 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\. As shown in the screenshot below, by clicking the "+" button next to "Active flows", you can select the algorithms you want to use for signal processing. Select the sensor for which you want to apply the ECG R-Notebook in the drop-down "Device" menu. Select the algorithms in the drop-down “Algorithm” menu and 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.

***Note:*** *it is possible now (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 two Shimmer devices here by adding two Active flows with the devices you would like to analyze on.*

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

***For BLE sensors***, you can also choose whether to “Disable IBI detrend (to support long recordings)” or not as shown in the screenshot below. Due to the signal properties from BLE sensors, peak detection calculation will be skipped. The algorithm will be explained more in the section Algorithm Introduction.

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

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

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

## 2. Algorithm Introduction

### (1) ECG Peak Detection

#### For ECG signal from Shimmer, Biopac, Biopac Bionomadix, ABM B-Alert ECG channel and Biosignal Plux that stream in raw ECG:

1. *Shimmer ECG ONLY*: by defining parameter **\[Shimmer ECG channel name]**: "ECG LL-RA CAL" or “ECG LA-RA CAL”, you can choose which channel you want to apply the R-Notebook on.
2. The signal is first bandpassed to reduce the influence of muscle noise, powerline noise (US 60 Hz ; Europe 50 Hz), baseline wander, and T-wave interference. A classic [Butterworth](https://en.wikipedia.org/wiki/Butterworth_filter) band-pass filter with a total order of 4 is applied. The desirable passband to maximize the [QRS](https://en.wikipedia.org/wiki/QRS_complex) energy is approximately 5-15 Hz (Goovaerts et al. 1976),(Thakor, Webster, and Tompkins 1983). The passband used in this analysis is between the **\[Band-pass filter low cuttoff frequency \[in Hz]]** and **\[Band-pass filter high cuttoff frequency \[in Hz]]** (default value 5 - 15 HZ). The filtering process was performed in forward and reverse direction. Data points with an absolute value superior to the selected **Artefact threshold \[in mV]** (default 5 mV) are considered outliers and removed for further analysis. The filtered signal is then normalized in arbitrary units between 0 and 1000.
3. Detection of possible peaks inside QRS region: a squared double difference method is applied to the filtered signal (Sadhukhan and Mitra 2012). The maximum is calculated of the difference signal and a possible peak is marked every time the difference signal crosses above 3% of the maximum. Since the maximum duration of the QRS regions is 150 ms, to eliminate unwanted peaks inside the same QRS region windowing is applied with a size +-75 of the current peak. If multiple peaks are inside the window only the peak with the biggest amplitude of the difference signal is saved. Inside each QRS window the mean of the maximum and the minimum of the raw ECG data was calculated to get the relative magnitudes. The maximum of the relative magnitudes inside the QRS region is the new R-peak as the former detected peak could have been the S point.
4. The adaptive algorithm runs through the possible peaks to identify the real peaks: To ensure detection accuracy certain criteria of the RR-intervals are processed. Minimum difference between R peaks is considered to be 200 ms. Any peaks detected within this window, from the peak with the biggest amplitude to the smallest, are removed. In addition the RR-intervals are also checked according to two cases:

   1. Case 1: The distance between the two peaks is less than 70% of the average distance. In this case peaks are removed.
   2. Case 2: The distance between the two peaks is more than 180% of the average distance. In this case the peak detection method described above is repeated only for this window.

   The average distance is calculated based on the average distance of the peak with the biggest amplitude and the surrounding 4 peaks. We expect the lowest average pulse of a recording to be 50 bpm and the highest average pulse to be 120 bpm. If the average distance shows to have a smaller/larger pulse, based on the distance of the peaks, it is with high possibility that artifacts are present in the data. In this case we use a default value (average distance = 800 ms) corresponding to the pulse being 75 bpm. This verification of the two cases is done from the peak with the biggest amplitude value to the peak with the smallest. If one peak is kept it cannot be removed later on. This is to eliminate the case, where a correct peak is removed over an incorrect peak.
5. Once the peaks are selected ‘missed peaks’ are marked, where the difference in the timestamps, between the peaks becomes, larger than 180% of the average distance. Based on that the **I**nter-**B**eat **I**nterval (**IBI**) and **h**eart **r**ate (**HR**) signals are computed.
6. To calculate the time domain metrics (**R**oot **M**ean **S**quare of **S**uccessive **D**ifferences (RMSSD) (ms) and **S**tandard **D**eviation of **N**ormal-to-**N**ormal Intervals (SDNN) (ms)), cubic spline interpolation is first applied at the removed IBI data points. The interpolated IBIs are then detrended to obtain [stationary signals](https://en.wikipedia.org/wiki/Stationary_process). An advanced detrending procedure based on smoothness priors approach is applied (Tarvainen, Ranta-aho, and Karjalainen n.d.). The smoothing parameter lambda is set to 500, which equals a cutoff frequency of 0.035 Hz. The method operates like a time-varying highpass filter, smoothing the data according to the value of the smoothing parameter lambda. The bigger the smoothing parameter is, the lower the cutoff frequency of the filter will be.
7. To calculate the frequency domain metrics the conversion of time domain into the frequency domain is needed, which is done through the calculation of the power spectral density (PSD). This is based on the IBI detrended signal, with the same method used for the time domain, but with a sampling frequency of 4 Hz for the interpolation (Heine et al. 2017). The Welch method, which uses the [Fast-Fourier Transformation (FFT)](https://en.wikipedia.org/wiki/Fast_Fourier_transform), is used for the estimation of PSD. For the window overlapping the method [Hann window](https://en.wikipedia.org/wiki/Hann_function) is applied with a window width of 64 s (the same as 256 sample points) and with 50% overlap between neighboring windows. The PSDs from all windows are then averaged to get the PSD signal. This method has been selected to create a more robust estimation of the PSD signal. The PSD signal is divided into three frequency intervals; **Very low frequencies \[in Hz]** (VLF, default span from 0.0033 - 0.04 Hz), **Low frequencies \[in Hz]** (LF, default span from 0.04 - 0.15 Hz) and **High frequencies \[in Hz]** (HF, default span from 0.15 - 0.4 Hz), where the spectral power is calculated as the area under the curve (AUC) of each interval. If the **Compute normalized frequency metrics** are checked off, the normalized frequency metrics is calculated by taking either high or low frequency and divide it with the sum of high and low frequency and multiply it with 100. The relative frequency metrics is calculated by taking either high or low frequency and divide it with the total power (the sum of all frequencies: TP = HF + LF + VLF) and multiply it with 100 (Shaffer and Ginsberg 2017).

> Note
>
> *Please ensure a duration of at least* ***64 seconds*** *for the notebook to deliver any frequency metrics data.*

#### For ECG signal from BLE sensors that stream in R-R intervals signals:

1. The Inter-Beat Interval (IBI) signal (same as R-R interval) is directly retrieved from the raw data. The heart rate signal is then calculated based on the IBI signal: heart\_rate=1000\* 60/IBI\_signal
2. To calculate the time domain metrics (RMSSD (ms) and SDNN (ms)): The IBIs signals are first detrended to obtain [stationary signals](https://en.wikipedia.org/wiki/Stationary_process). An advanced detrending procedure based on smoothness priors approach is applied (Tarvainen, Ranta-aho, and Karjalainen Feb./2002). The smoothing parameter lambda is set as 500, which equals a cutoff frequency of 0.035 Hz. The method operates like a time-varying highpass filter, smoothing the data according to the value of the smoothing parameter lambda. The bigger the smoothing parameter is, the lower the cutoff frequency of the filter will be.
3. To calculate the frequency domain metrics the conversion of time domain into the frequency domain is needed, which is done through the calculation of the power spectral density (PSD). This is based on the IBI detrended signal, with the same method used for the time domain, but with a sampling frequency of 4 Hz for the interpolation (Heine et al. 2017). The Welch method, which uses the [Fast-Fourier Transformation (FFT)](https://en.wikipedia.org/wiki/Fast_Fourier_transform), is used for the estimation of PSD. For the window overlapping the method [Hann window](https://en.wikipedia.org/wiki/Hann_function) is applied with a window width of 64 s (the same as 256 sample points) and with 50% overlap between neighboring windows. The PSDs from all windows are then averaged to get the PSD signal. This method has been selected to create a more robust estimation of the PSD signal. The PSD signal is divided into three frequency intervals; **Very low frequencies \[in Hz]** (VLF, default span from 0.0033 - 0.04 Hz), **Low frequencies \[in Hz]** (LF, default span from 0.04 - 0.15 Hz) and **High frequencies \[in Hz]** (HF, default span from 0.15 - 0.4 Hz), where the spectral power is calculated as the area under the curve (AUC) of each interval. If the **Compute normalized frequency metrics** is checked off, the normalized frequency metrics is calculated by taking either high or low frequency and divide it with the sum of high and low frequency and multiply it with 100. The relative frequency metrics is calculated by taking either high or low frequency and divide it with the total power (the sum of all frequencies: TP = HF + LF + VLF) and multiply it with 100 (Shaffer and Ginsberg 2017).

> Note
>
> *Please ensure a duration of at least* ***64 seconds*** *for the notebook to deliver any frequency metrics data.*

#### For ECG signal from BLE sensors that stream in only Heart rate signals:

The Heart Rate metrics is calculated as the overall mean of the ‘Heart rate’ signal. The HRV metrics will not be calculated due to the missing of R-R intervals.

#### For PPG signals from Shimmer, Biopac and Biosignal Plux:

1. The signal is first bandpassed to reduce the influence of muscle noise, powerline noise (US 60 Hz ; Europe 50 Hz) and baseline wander. A classic Butterworth band-pass filter with a total order of 2 is applied. The desirable passband to maximize the PPG cycle is approximately 0.5-8 Hz. (Elgendi et al. 2013). The passband used in this analysis is between 0.5 and 8 Hz.
2. Detection of possible systolic peaks inside the PPG cycle: First the filtered signal is squared to emphasise the large differences resulting from the systolic wave, which suppress the small differences arising from the diastolic wave and noise. Then blocks of interest are generated. This is done by using two event-related moving averages that demarcate the systolic and heartbeat areas. The first moving average (MA\_peak) is used to emphasise the systolic peak area and given by the following formula: MA\_peak\[n] = 1 / W\_1 \* (y\[n − (W\_1 − 1) / 2] + ... + y\[n] + ... + y\[n + (W\_1 − 1) / 2]) where W\_1 is the window size of the systolic peak duration, determined to be 111 ms (Elgendi et al. 2013). The second moving average (MA\_beat) is used to emphasise the beat area to be used as a threshold for the first moving average and given by the following formula: MA\_beat\[n] = 1 / W\_2 \* (y\[n − (W\_2 − 1) / 2] + ... + y\[n] + ... + y\[n + (W\_2 − 1) / 2]) where W\_2 represents the window size of approximately one beat duration, determined to be 667 ms (Elgendi et al. 2013). Next the blocks of interest are selected, so only the actual blocks containing the systolic peak are kept. This is done using thresholding. The first dynamic threshold value is calculated by shifting the MA\_beat signal with an offset level α as follows: THR1 = MA\_beat\[n] + α where α = βz¯ and where β = 0.02 and z¯ is the statistical mean of the squared filtered PPG signal. The blocks of interest are assigned the value 0.1 if MA\_peak\[n] are larger than THR1 and assigned 0 if not. The second dynamic threshold will remove blocks that are not wide enough to contain the systolic peak. This is done using THR2 = W\_1, where if blocks are wider or equal to THR2 then the blocks are kept and discarded if not. The last step is to find the maximum absolute value inside the remaining blocks to detect the systolic peaks.
3. The detected peaks are then filtered based on the following case: If the distance between the two peaks is less than 70% of the median distance, peaks are removed.

   The median distance is calculated based on the median distance of the peak with the biggest amplitude and the surrounding 4 peaks. We expect the lowest median pulse of a recording to be 50 bpm and the highest median pulse to be 120 bpm. If the median distance shows to have a smaller/larger pulse, based on the distance of the peaks, it is with high possibility that artifacts are present in the data. In this case we use a default value (median distance = 800 ms) corresponding to the pulse being 75 bpm. This verification is done from the peak with the biggest amplitude value to the peak with the smallest. If one peak is kept it cannot be removed later on. This is to eliminate the case, where a correct peak is removed over an incorrect peak.
4. Once the peaks are selected ‘missed peaks’ are marked, where the difference in the timestamps between the peaks becomes larger than 180% of the median distance. Based on that the Inter-Beat Interval (IBI) and heart rate (HR) signals are computed.
5. To calculate the time domain metrics, cubic spline interpolation is first applied at the removed IBI data points. The interpolated IBIs are then detrended to obtain stationary signals. An advanced detrending procedure based on smoothness priors approach is applied (Tarvainen, Ranta-aho, and Karjalainen n.d.). The smoothing parameter lambda is set to 500, which equals a cutoff frequency of 0.035 Hz. The method operates like a time-varying highpass filter, smoothing the data according to the value of the smoothing parameter lambda. The bigger the smoothing parameter is, the lower the cutoff frequency of the filter will be.
6. To calculate the frequency domain metrics the conversion of time domain into frequency domain is needed, which is done through the calculation of the power spectral density (PSD). This is based on the IBI detrended signal, with the same method used for the time domain, but with a sampling frequency of 4 Hz for the interpolation (Heine et al. 2017). The Welch method, which uses the Fast-Fourier Transformation (FFT), is used for the estimation of PSD. For the window overlapping the method Hann window is applied with a window width of 64 s (the same as 256 sample points) and with 50% overlap between neighboring windows. The PSDs from all windows are then averaged to get the PSD signal. This method has been selected to create a more robust estimation of the PSD signal. The PSD signal is divided into three frequency intervals; very low frequency (VLF, span from 0.0033 - 0.04 Hz), low frequency (LF, span from 0.04 - 0.15 Hz) and high frequency (HF, span from 0.15 - 0.4 Hz), where the spectral power is calculated as the area under the curve (AUC) of each interval.
7. The normalized frequency metrics is calculated by taking either high or low frequency and divide it with the sum of high and low frequency and multiply it with 100. The relative frequency metrics is calculated by taking either high or low frequency and divide it with the total power (the sum of all frequencies: total power = HF + LF + VLF) and multiply it with 100 (Shaffer and Ginsberg 2017).

> Note
>
> *Please ensure a duration of at least* ***64 seconds*** *for the notebook to deliver any frequency metrics data.*

### (2) Momentary HRV Calculation

1. To calculate the momentary HRV calculation: the length of the available ECG signal is first checked to see whether it is longer than **\[Momentary HRV moving window length \[s]]** (300 seconds (5 min) as default). The following calculations will only be conducted if this condition is fulfilled.
   1. the raw IBI time-series from peak detection is first interpolated and downsampled to 4 Hz.
   2. The IBI time-series is then detrended to obtain [stationary signals](https://en.wikipedia.org/wiki/Stationary_process). An advanced detrending procedure based on smoothness priors approach is applied (Tarvainen, Ranta-aho, and Karjalainen Feb./2002). The smoothing parameter lambda is set as 500, which equals a cutoff frequency of 0.035 Hz.
   3. The adaptive algorithm runs through the interpolated and detrended IBI time-series to calculate the variability time-series: a moving window of **\[Momentary HRV moving window length \[s]]** (300 seconds (5 min) as default) advancing with a time step of **\[Momentary HRV window increment step \[s]]** (60 seconds (1 min) as default) is used. For each window, the SDNN or the RMSSD is calculated. You can choose whether to run the SDNN or the RMSSD when scrolling down in that section of the software **\[Momentary HRV calculation method]**.

{% hint style="info" %}
A moving window of at least **5 minutes** is recommended for short-term HRV analysis (Heart J 1996) and has been applied for capturing momentary HRV with a recommended increment step of 1 minute (Zhang et al. 2015). To make use of all the data, the increment step of each moving window should be shorter than or equal to the moving window length.
{% endhint %}

Once the variability time-series is generated, a corresponding step plot is generated: x axis denotes the time spent since the stimulus starts, y axis denotes the calculated momentary HRV.

Momentary HRV algorithm schematic graph:

Example: **\[Momentary HRV moving window length \[s]]** 300 seconds (5 min) and **\[Momentary HRV window increment step \[s]]** 60 seconds (1 min) are used in this example to calculate momentary SDNN:

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

## 3. The Outputs

### (1) Desktop replay:

#### If you are analyzing ECG signals from Shimmer, Biopac, Biopac Bionomadix, Biosignal Plux that stream in raw ECG signals, or BLE sensors that stream in R-R intervals signals like Polar Belt H10 or PPG sensors:

In the individual replays of data, the detected peaks and calculated metrics/signals are displayed as follows:

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

* **ECG Metrics:**
  * **\[Percentage of missed peaks (%)]**: the percentage of missed peaks out of all detected peaks.

    > Notes
    >
    > Please note that this metric is not computed for BLE sensors like Polar Belt H10.
  * **\[Average Heart Rate (beat/minute)]**: the average beat per minute the respondent had during this stimulus/scene. Calculated from raw IBI time-series before any interpolation and detrending.
  * **\[Average IBI (ms)]**: the average inter-beat intervals the respondent had during this stimulus/scene. In the unit of millisecond. Calculated from raw IBI time-series before any interpolation and detrending.
  * **\[RMSSD (ms)]**: the overall root mean square of successive differences between normal heartbeats the respondent had during this whole stimulus/scene. In the unit of millisecond. Calculated from interpolated and detrended IBI time-series.
  * **\[SDNN (ms)]**: the overall standard deviation of IBIs the respondent had during this whole stimulus/scene. In the unit of millisecond. Calculated from interpolated and detrended IBI time-series.
  * **\[VLF Power (ms²)]**: Absolute power of the very-low-frequency band, of the IBIs the respondent had during this whole stimulus/scene.
  * **\[LF Power (ms²)]**: Absolute power of the low-frequency band, of the IBIs the respondent had during this whole stimulus/scene.
  * **\[HF Power (ms²)]**: Absolute power of the high-frequency band, of the IBIs the respondent had during this whole stimulus/scene.
  * **\[LF/HF]**: Ratio of LF-to-HF power, of the IBIs the respondent had during this whole stimulus/scene.
  * **\[Normalized LF Power (%)]**: Normalized power of the low-frequency band, of the IBIs the respondent had during this whole stimulus/scene. It is computed by taking low frequency and dividing it with the sum of high and low frequency and multiply it with 100. Simplified as LF Power (ms²)/(LF Power (ms²) + HF Power (ms²)) \* 100%
  * **\[Normalized HF Power (%)]**: Normalized power of the high-frequency band, of the IBIs the respondent had during this whole stimulus/scene. It is computed by taking high frequency and dividing it with the sum of high and low frequency and multiply it with 100. Simplified as HF Power (ms²)/(LF Power (ms²) + HF Power (ms²)) \* 100%
  * **\[Relative LF Power (%)]**: Relative power of the low-frequency band, of the IBIs the respondent had during this whole stimulus/scene. It is calculated by taking low frequency and divide it with the total power (the sum of all frequencies: TP = HF + LF + VLF) and multiply it with 100%. Simplified as LF Power (ms²)/(total power (ms²)) \* 100%
  * **\[Relative HF Power (%)]**: Relative power of the high-frequency band, of the IBIs the respondent had during this whole stimulus/scene. It is calculated by taking high frequency and divide it with the total power (the sum of all frequencies: TP = HF + LF + VLF) and multiply it with 100%. HF Power (ms²)/(total power (ms²)) \* 100%
* **ECG Signals**:
  * **\[R Peak Detection]**: R Peaks Occurrences. R peak samples are assigned a value of "1". Other samples outside the peak are assigned a value of "0".

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

    > Notes:
    >
    > Please note that this signal is not computed for BLE sensors like Polar Belt H10.
  * **\[Heart Rate]**: the running heart rate with each step value calculated from the corresponding IBI of two consecutive detected peaks.

    > Notes:
    >
    > Please note that this metric is not computed for BLE sensors like Polar Belt H10.
  * **\[Momentary HRV]**: the running momentary HRV signal with a step duration of **\[Momentary HRV window increment step \[s]]** represents the HRV values calculated from the moving window of **\[Momentary HRV moving window length \[s]]**. There can be an absence of signals near the end of the stimulus due to insufficient signal length.

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

#### If you are analyzing BLE sensors that ONLY stream in Heart Rate signals:

* **ECG Metrics:** Average Heart Rate (beat/minute) will be calculated and displayed.
* **ECG Signals:** There will be no calculation or display of signals for this type of BLE sensor in the desktop replay.

### (2) Exported files:

There are three types of files you can access: Sensor Data file, and 2 files from R processing (**ECGMetrics** and **ECGPeakTable**).

* **Sensor Data file:** raw sensor data export. It can also include R-processed signals by ticking the "R analysis Heart rate and Heart rate variability processing” as shown in step 5, as shown in the screenshots below. For iMotions 10.2 and earlier iMotions versions, to do that you will need to select the “Processed and imported data" option instead.

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

and then:

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

* **ECGMetrics file:** 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 the 'Peak metrics' exports , and then (4) click on 'Export' button to generate the file.
* **ECGPeakTable file:** from iMotions 10.4 and onwards. To get this file, select the ‘Peak table’ option as shown in the screenshot below. This export file specifies the **Peak index, Peak time and inter-beat interval** of every ECG peak (QRS segment) of every stimulus and, if you select the “include annotations in the peak table” option, of every annotation as well.

Please refer to [***this article***](https://help.imotions.com/lab/exports/r-processed-exports/export-r-processed-ecg-files.md) for a detailed description of all the exported files.

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-d4c54f4caa3970998a55be8c77a8f41e10e8e911%2F7e32697bc1_Exporting-summary-metrics-and-peaktable.webp?alt=media)

### (3) Reports:

A one-page readout is generated, along with presenting the actual R Code used to calculate the results, descriptions of each of the analysis steps, and links to the articles that were referred to when writing the algorithm’s script.

In brief, to find the Reports file:

1. Click the Reports button shown in the screenshot in the section above
2. As a result of that, you will be able to open the HTML report for every stimulus of your choice to see the R-Notebook readout.

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

   In the opened Report, one can also find the overview of R Notebook results in both plots and metrics. For Heart Rate and Heart Rate Variability R Notebook, there will also be a spectrogram of the signal that describes the power spectral density (PSD) present in the signal as a function of frequency (as shown below).

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

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

   One can also use Reports to find troubleshooting information. For example, as shown below, the R Notebook can not run due to too short stimulus duration. This type of information will be provided in the Report.

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

## References

Goovaerts, Henk G., Henk H. Ros, Van Den AkkerThomas J., and Hans Schneider. 1976. “A Digital QRS Detector Based on the Principle of Contour Limiting.” *IEEE Transactions on Biomedical Engineering* BME-23 (2): 154–60. <https://doi.org/10.1109/TBME.1976.324577>.

Heart J, Eur. 1996. “Heart Rate Variability Standards of Measurement, Physiological Interpretation, and Clinical Use.” *Eur Heart J* 17: 28.

Heine, T., G. Lenis, P. Reichensperger, T. Beran, O. Doessel, and B. Deml. 2017. “Electrocardiographic Features for the Measurement of Drivers’ Mental Workload.” Applied Ergonomics 61 (January): 31–43.

Jeyhani, Vala, Shadi Mahdiani, Mikko Peltokangas, and Antti Vehkaoja. 2015. “Comparison of HRV Parameters Derived from Photoplethysmography and Electrocardiography Signals.” In *2015 37th Annual International Conference of the IEEE Engineering in Medicine and Biology Society (EMBC)*, 5952–5. Milan: IEEE. <https://doi.org/10.1109/EMBC.2015.7319747>.

Shaffer, F., and J. P. Ginsberg. 2017. “An Overview of Heart Rate Variability Metrics and Norms,” September.

Tarvainen, M.P., P.O. Ranta-aho, and P.A. Karjalainen. Feb./2002. “An Advanced Detrending Method with Application to HRV Analysis.” *IEEE Transactions on Biomedical Engineering* 49 (2): 172–75. <https://doi.org/10.1109/10.979357>.

Thakor, N. V., J. G. Webster, and W. J. Tompkins. 1983. “Optimal QRS Detector.” *Medical & Biological Engineering & Computing* 21 (3): 343–50. <https://doi.org/10.1007/BF02478504>.

Zhang, Haoshi, Mingxing Zhu, Yue Zheng, and Guanglin Li. 2015. “Toward Capturing Momentary Changes of Heart Rate Variability by a Dynamic Analysis Method.” Edited by Xiongwen Chen. *PLOS ONE* 10 (7): e0133148. <https://doi.org/10.1371/journal.pone.0133148>.

Elgendi, M., I. Norton, M. Brearley, D. Abbott, and D. Schuurmans. 2013. “Systolic Peak Detection in Acceleration Photoplethysmograms Measured from Emergency Responders in Tropical Conditions,” October.


---

# 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/biosensor-analysis/r-notebooks-ecg-heart-rate-and-hrv-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.
