# Q-14: Heart rate from beat intervals

Data-Driven Athletics tutorial · Week 5 · Chapter 5 · about 15 min · workflow steps: Gather, Statistics, Visualize, Features

Web page: https://apopt.com/course/tutorials/q14-hr-from-rr/ · Data: https://apopt.com/data/tutorials/q14-hr-from-rr/

## The decision

An athlete asks for the average and the peak heart rate of a short session. Which number from
the strap answers each, and how should the average be computed?

## The raw data

- `raw/2026-06-27_1810_day.csv.gz`: eight minutes of the instructor's chest-strap ECG with the strap's RR intervals and displayed heart rate (columns time, ecg, hr, rr, marker; gzip) The instructor's own Polar H10 recording, 27 June 2026, from the course case file `athletes/jh/heart/`, published under his name.

A chest strap reports two things: the time between beats (the RR interval, in milliseconds)
and a heart rate for its display. They are not the same number. This file is eight minutes of
the instructor wearing a Polar H10: quiet at first, then two short efforts, then rest. Every
ECG sample is a row; the `rr` column is filled on the rows where the strap reported a beat
interval, and the `hr` column on the rows where it reported its displayed heart rate.

### Separate the beats from the display

*Predict first:* The session lasts about 8 minutes at an average near 80 beats a minute. How many beat intervals do you expect?

```python
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/2026-06-27_1810_day.csv.gz")       # pandas reads the gzip directly
t = (raw["time"] - raw["time"].iloc[0]) / 1e9               # seconds from the start
beats = pd.DataFrame({"t": t[raw["rr"].notna()], "rr": raw["rr"].dropna()})
shown = pd.DataFrame({"t": t[raw["hr"].notna()], "hr": raw["hr"].dropna()})
print(f"{len(raw)} rows over {t.iloc[-1]:.1f} s ({t.iloc[-1] / 60:.1f} min)")
print(f"{len(beats)} beat intervals, {len(shown)} displayed heart rates")
print(f"RR from {beats['rr'].min():.0f} to {beats['rr'].max():.0f} ms; "
      f"intervals add up to {beats['rr'].sum() / 1000:.1f} s")
```

Output:

```
65189 rows over 500.7 s (8.3 min)
673 beat intervals, 500 displayed heart rates
RR from 421 to 1436 ms; intervals add up to 499.9 s
```

The intervals add up to within a second of the recording's length, as they should if no
beat is missing. A missed beat would leave a gap of a whole interval.

### Heart rate, beat by beat

One beat that lasts RR milliseconds is a heart rate of 60 000 / RR beats a minute. That gives
a heart rate for every beat. Now average it over the session, two ways.

*Predict first:* Will the mean of the beat-by-beat heart rates equal 60 000 divided by the mean RR interval?

```python
beats["hr"] = 60000 / beats["rr"]
per_beat = beats["hr"].mean()                       # every beat counts once
per_time = 60000 / beats["rr"].mean()               # beats counted per minute of time
print(f"mean of the beat heart rates   {per_beat:.1f} beats/min")
print(f"60 000 / mean RR               {per_time:.1f} beats/min")
print(f"beats / minutes                {len(beats) / (beats['rr'].sum() / 60000):.1f} beats/min")
print(f"strap's displayed mean         {shown['hr'].mean():.1f} beats/min")
```

Output:

```
mean of the beat heart rates   90.1 beats/min
60 000 / mean RR               80.8 beats/min
beats / minutes                80.8 beats/min
strap's displayed mean         81.1 beats/min
```

They differ by about 9 beats a minute. A fast beat is short, so a minute of hard work holds
many more beats than a minute of rest, and averaging over beats lets the hard minutes count
too often. The heart rate of a session is beats divided by minutes, which is 60 000 divided by
the mean interval. The strap's display agrees with that one.

### Beat by beat against the display

*Predict first:* Which will be higher, the highest single-beat heart rate or the highest the strap displayed?

```python
import matplotlib.pyplot as plt

five = 60000 / beats.groupby(beats["t"] // 5)["rr"].mean()   # 5-second bins, beats per minute of time
print(f"highest single beat {beats['hr'].max():.1f} at {beats.loc[beats['hr'].idxmax(), 't'] / 60:.1f} min")
print(f"highest 5-second rate {five.max():.1f}; highest displayed {shown['hr'].max():.0f} beats/min")

fig, ax = plt.subplots(figsize=(9, 3.4))
ax.plot(beats["t"] / 60, beats["hr"], ".", ms=3, label="from each RR interval")
ax.plot(shown["t"] / 60, shown["hr"], "-", lw=1.5, color="k", label="strap's display")
ax.set(xlabel="time (min)", ylabel="heart rate (beats/min)")
ax.legend(loc="upper left")
plt.tight_layout()
```

Output:

```
highest single beat 142.5 at 4.0 min
highest 5-second rate 133.4; highest displayed 134 beats/min
```

![Heart rate in beats per minute against time in minutes. Dots, one per beat from the RR intervals, follow two efforts up to about 134; a few dots sit far from their neighbours, the highest at 142 near minute 4. The strap's displayed heart rate, a line, follows the dots smoothly.](https://apopt.com/course/tutorials/q14-hr-from-rr/c05-1.png)

The highest single beat, 142.5 beats a minute, sits alone, about 30 above the beats on either
side of it. A heart does not jump that far for one beat during steady effort: a beat was
mistimed, or a noise spike was counted. A few more such dots sit near minute 5.8. Averaged over
five seconds, the peak is 133.4, and the strap's smoothed display, 134, agrees. Use the
intervals for anything that changes within seconds, but never report one beat as a peak.
Chapter 5 shows the rules that remove such beats; Q-15 uses one.

**For the athlete:** "Your heart rate over this session averaged about 81 beats a minute, and
your peak was about 134; one beat that read 142 was a glitch, not you."

## With your own data

Record a few minutes of rest and a short effort with the Heart app (or any logger that writes
the same columns), open your file in place of this one, and check that your intervals add up to
the recording length before you trust any average.

## Action card

- **Finding:** The session's heart rate was 80.8 beats a minute and its peak about 134.
- **Evidence:** Beats divided by minutes and 60 000 over the mean interval agree; the mean of the beat rates (90.1) overcounts the fast beats. The 5-second peak (133.4) agrees with the display (134).
- **Sure:** High; the intervals add up to within a second of the recording's length, so no beats are missing.
- **Action:** Report session averages as beats per minute of time, and peaks as a short average, never a single beat.
- **Retest:** Check the interval total against the recording length on every new file.

## References

- *Data-Driven Athletics*, Chapter 5, From ECG to Beats (Section 5.4) and How Heart Rate Answers Exercise (Section 5.6).

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
