Code
if(!requireNamespace("remotes")) {
install.packages("remotes")
}
remotes::install_github("grimbough/FITfileR")
library("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")
}
remotes::install_github("grimbough/FITfileR")
library("FITfileR")
library(tidyverse)TargetDir <- paste(as.character(tkchooseDirectory(title = "Select the fit data folder"),sep = "", collapse =""))
setwd(TargetDir)FIT files stored in the folder are read into FitNameList.
FitNameList <- list.files(path = TargetDir) %>%
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)
FileNo <- 2
ReadFit <- readFitFile(FitNameList[FileNo])
ReadFit # checkFit 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
RecodeData <- getMessagesByType(ReadFit,
message_type = "record")
#RecodeData #check
#データ格納用引数
MasterRecord <- NULL
#RecodeData分の繰り返し処理
for(i in seq(RecodeData)){
Recode <- bind_cols("id" = i, RecodeData[[i]])
MasterRecord <- bind_rows(MasterRecord, Recode)
}
#日付けデータを変換する
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
df <- MasterRecord %>%
select(timestamp, heart_rate) %>%
na.omit()setwd("~/Documents/brevet")
FileName <- paste0("time_hr_", FileNo, ".csv")
write.csv(df, file.path("csv_xls", file = FileName), row.names = FALSE)