Code
if(!requireNamespace("remotes")) {
install.packages("remotes")
}::install_github("grimbough/FITfileR")
remoteslibrary("FITfileR")
library(tidyverse)
1. Read Garmin FIT file and extract the necessary data for the RHRV analysis
Garmin’s cycle computers Edge series and smart-watches record activity information every second in real time. For example, heart rate, breathing rate and ride speed and so on. As they are equipped with GPS, information such as the latitude, longitude and altitude of the ride is also recorded.
The data is stored in a file called FIT. FIT is a binary file format developed by Garmin. It is a format that can be read by the FIT SDK provided by Garmin. The FIT SDK is available in C, C++, C#, Java, and Python. In addition, there are libraries that can be used in R. However, the libraries are not easy to use, and it is difficult to read the FIT file in R.
This section provides instructions on how to load a FIT file in R and extract the necessary data for the RHRV analysis.
if(!requireNamespace("remotes")) {
install.packages("remotes")
}::install_github("grimbough/FITfileR")
remoteslibrary("FITfileR")
library(tidyverse)
<- paste(as.character(tkchooseDirectory(title = "Select the fit data folder"),sep = "", collapse =""))
TargetDir
setwd(TargetDir)
FIT files stored in the folder are read into FitNameList.
<- list.files(path = TargetDir) %>%
FitNameList str_extract("^.*fit*$") %>%
na.omit()
head(FitNameList, 4) # check
[1] "12509331867_ACTIVITY 2.fit" "12509331867_ACTIVITY.fit"
If the FIT file is the third, give 3 to FileNo. FileNo <- 65
setwd(TargetDir)
<- 2
FileNo <- readFitFile(FitNameList[FileNo])
ReadFit # check ReadFit
Fit File
├╴File created: 2023-10-29 00:00:05
├╴Device: garmin fenix7x_apac
└╴Number of data messages: 40789
listMessageTypes(ReadFit) # check
[1] "file_id" "device_settings" "user_profile" "zones_target"
[5] "sport" "session" "lap" "record"
[9] "event" "device_info" "activity" "file_creator"
[13] "training_file" "hrv" "gps_metadata"
“records” often contain data such as heart rat, speed, etc.
#Read the record message
<- getMessagesByType(ReadFit,
RecodeData message_type = "record")
#RecodeData #check
#データ格納用引数
<- NULL
MasterRecord
#RecodeData分の繰り返し処理
for(i in seq(RecodeData)){
<- bind_cols("id" = i, RecodeData[[i]])
Recode <- bind_rows(MasterRecord, Recode)
MasterRecord
}
#日付けデータを変換する
<-
MasterRecord %>%
MasterRecord mutate_if(is.POSIXt, ~with_tz(., tz = "Asia/Tokyo"))
#MasterRecordを時間で並び替え
<- MasterRecord %>%
MasterRecord arrange(timestamp)
if(!require("openxlsx", quietly = TRUE)){
install.packages("openxlsx");require("openxlsx")
}
# Extract heart_rate
<- MasterRecord %>%
df select(timestamp, heart_rate) %>%
na.omit()
setwd("~/Documents/brevet")
<- paste0("time_hr_", FileNo, ".csv")
FileName
write.csv(df, file.path("csv_xls", file = FileName), row.names = FALSE)