About the Package

The pelotonR package was created to provide users with simple access to the Peloton API through R.

The Peloton APIs are unsupported. However, there are some really great unofficial swagger docs which I used to familiarize myself with the API.


The package offers a set of easy to use functions which allow the user to:

Load the Libraries

Before we start exploring the pelotonR package, we will load a few libraries used to help explore and display the data.

#Uncomment the line below if you also need to install pelotonR
# devtools::install_github("lgellis/pelotonR")
library("pelotonR")
#Packages for nice output display
library(DT) # For table display
library(Hmisc) # For list display
## Loading required package: lattice
## Loading required package: survival
## Loading required package: Formula
## Loading required package: ggplot2
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
## 
##     format.pval, units
library(tidyverse) # For data munging
## ── Attaching packages ──────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble  3.0.1     ✓ dplyr   1.0.0
## ✓ tidyr   1.1.0     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ✓ purrr   0.3.4
## ── Conflicts ─────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter()    masks stats::filter()
## x dplyr::lag()       masks stats::lag()
## x dplyr::src()       masks Hmisc::src()
## x dplyr::summarize() masks Hmisc::summarize()
library(lubridate) # For dates
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(gameofthrones) # For colors

Unauthenticated API Calls

The following functions are available without authentication.

Get Peloton Metadata Mappings Data Frame

The function get_metadata_mapping_df(type) allows us to see all metadata mapping for a particular category of Peloton metadata. Available options for type include: ‘instructors’, ‘class_types’, ‘equipment’, ‘fitness_disciplines’, device_type_display_names’, ‘content_focus_labels’, ‘difficulty_levels’, ‘locales’

To learn about the function, execute the command ?get_metadata_mapping_df

class_types <- get_metadata_mapping_df('class_types')

#Nicely display data
datatable(class_types, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Get Peloton Live Rides Data Frame

The function get_live_rides_df returns a data frame with all of the currently available live rides.

To learn about the function, execute the command ?get_live_rides_df

live_rides <- get_live_rides_df()

#Nicely display data
datatable(live_rides, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Get Full Set of Ride Information In a List

The function get_ride_info_list allows us to gather the full list of information for a particular ride.

To learn about the function, execute code ?get_ride_info_list

ride_info <- get_ride_info_list('55214456a1984c5885a087021e3f67b7')

#Nicely display data
list.tree(ride_info)
##  ride_info = list 60 (20624 bytes)
## .  class_type_ids = character 1= 7579b9edbdf9464fa19eb5 
## .  content_provider = character 1= peloton 
## .  content_format = character 1= video 
## .  description = character 1= Efficient and effectiv 
## .  difficulty_estimate = double 1= 8.0285
## .  overall_estimate = double 1= 0.9955
## .  difficulty_rating_avg = double 1= 8.0285
## .  difficulty_rating_count = integer 1= 26062
## .  difficulty_level = NULL 0
## .  duration = integer 1= 900
## .  equipment_ids = list 0
## .  equipment_tags = list 0
## .  ...   and 48 more

Get Peloton Ride Data Frame

The function get_ride_info_df allows us to gather the basic ride information for a particular ride into a data frame.

To learn about the function, execute the command `?get_ride_info_df

ride_info <- get_basic_ride_info_df('55214456a1984c5885a087021e3f67b7')

#Nicely display data
datatable(ride_info, extensions = "Scroller", width = 1000, options = list(scrollY = 75, scroller = TRUE, scrollX = 600, pageLength = 5))

Get Peloton Instructors Data Frame

The function get_instructors_df returns a data frame with all instructors and their information.

To learn about the function, execute the command ?get_instructors_df`

instructors <- get_instructors_df()

#Nicely display data
datatable(instructors, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Get Live Rides and Details

The function get_live_ride_and_details_df returns a data frame with all current live rides as well as the joined ride and instructor data for each ride.

To learn about the function, execute the command ?get_live_ride_and_details_df

live_with_details <- get_live_ride_and_details_df() 

#Nicely display data
datatable(live_with_details, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Plot Ride Data

Now that we have a data frame with all live rides and their metadata, we will do a simple plot to display some of the details of the live rides available. In this example, we are plotting the count of live rides by instructor.

p <- live_with_details %>%
  dplyr::group_by(instructor.name) %>%
  dplyr::summarize(N = length(instructor.name)) %>% 
  dplyr::filter(instructor.name !='NA') %>% 
  ggplot(aes(y=reorder(instructor.name, N), N) ) + 
  geom_bar(stat = "identity", fill= "#82B5C4") + 
  theme_light() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1), legend.position="bottom") +
  labs(title = "Current Live Rides Available by Instructor",
       x = "Total Rides", y = "Instructor", 
       caption = 'Source: @littlemissdata')
## `summarise()` ungrouping output (override with `.groups` argument)
p

Authenticate with Peloton

The function authenticate(username, password) allows the user to authenticate with the Peloton API. In this function you are able to pass in your username and password. If you pass in no value, the system will prompt you for a user name and password.

To learn about the function, execute the command ?authenticate

auth_response <-authenticate()
## Please enter password in TK window (Alt+Tab)
## Please enter password in TK window (Alt+Tab)
head(summary(auth_response))
##    Length     Class      Mode 
##         1      json character

Authenticated API Calls

The following functions are only available after the user has authenticated with the Peloton API. Authentication is easily done by calling the authenticate() function documented above.

Get My Workout Stats Data Frame

The function get_my_workout_stats_df() will gather the workout counts by category for the current authenticated user.

To learn about the function, execute the command ?get_my_workout_stats_df

workout_stats <-get_my_workout_stats_df()
datatable(workout_stats, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Plot Workout Stats Data Frame

When you get your workout stats using get_my_workout_stats_df(), you can plot a simple bar chart with ggplot2.

g <- workout_stats %>%
  ggplot(aes(x=factor(reorder(name, -count)), y=count)) +
  geom_bar(stat="identity", fill= "#82B5C4") +
  theme_light() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "Total Workout Stats",
       x = "Workout Type", y = "Count",
       caption = 'Source: @littlemissdata') 
g

Get My Stats List

The function get_my_stats_list() will gather all stats for the current authenticated user and return the results in a list.

To learn about the function, execute the command ?get_my_stats_list

stats <-get_my_stats_list()
head(summary(stats))
##                                 Length Class  Mode     
## id                              1      -none- character
## last_workout_at                 1      -none- numeric  
## phone_number                    1      -none- character
## has_active_digital_subscription 1      -none- logical  
## referral_code                   0      -none- NULL     
## default_heart_rate_zones        5      -none- numeric

Get My Workouts Data Frame

The function get_workouts_df() allows the user to gather all individual workouts for a specified user and return the results in a data frame. Note that if no user_id is passsed in, it will use the user id for the authenticated user. You can also pass in a specified user id. For example: get_workouts_df('n7u2739e18a7496fa146b3a42465da78').

To learn about the function, execute the command ?get_workouts_df

workouts <-get_workouts_df()  

#Drop personal information
workouts <- workouts%>% 
  dplyr::mutate(user_id = NULL)

#Nicely display data
datatable(workouts, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Get My Workouts with Instructor Information Data Frame

The function get_workouts_and_instructors_df() allows the user to gather all individual workouts and all related instructor data for a user and return it in a data frame. If a user id is not passed into the function, it will return the current users workouts.

To learn about the function, execute the command ?get_workouts_and_instructors_df

workouts_and_instructors <-get_workouts_and_instructors_df()

#Drop personal information
workouts_and_instructors <- workouts_and_instructors%>% 
  dplyr::mutate(workout.user_id = NULL)

#Nicely display data
datatable(workouts_and_instructors, extensions = "Scroller", width = 1000, options = list(scrollY = 400, scroller = TRUE, scrollX = 600, pageLength = 5))

Create some Fun Graphs

Progress Line Chart

When you get your workout stats, you can plot a simple progress line chart with ggplot2. The color palette is from the fabulous game of thrones package by Alejandro Jiménez.

p <- workouts_and_instructors %>%
  dplyr::group_by(workout.start_month, workout.fitness_discipline) %>%
  dplyr::summarize(N = length(workout.fitness_discipline)) %>% 
  ggplot(aes(x=workout.start_month, y=N, color=workout.fitness_discipline) ) + 
  geom_line() + 
  scale_fill_got(discrete = TRUE, option = "Margaery") +
  theme_light() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1), legend.position="bottom") +
  labs(title = "Workout by Month and Fitness Discipline",
       x = "Month", y = "Total Workouts", 
       caption = 'Source: @littlemissdata')
## `summarise()` regrouping output by 'workout.start_month' (override with `.groups` argument)
p

Favorite Cycling Instructors Overall

Note that the code for creating this donut plot is from r-graph-gallery.com.

g <- workouts_and_instructors %>%
  dplyr::filter(workout.fitness_discipline =='cycling') %>%
  dplyr::filter(workout.total_video_watch_time_seconds > 300) %>%
  dplyr::filter(instructor.name !="NA") %>%
  dplyr::group_by(instructor.name) %>%
  dplyr::summarize(N = length(instructor.name)) %>%
  dplyr::mutate(fraction = N/sum(N),
         ymax =cumsum(fraction),
         ymin = c(0, head(ymax, n=-1)),
         label = paste0(instructor.name, ": ", round(fraction,2) * 100, "%"),
         labelPosition = (ymax + ymin) / 2)
## `summarise()` ungrouping output (override with `.groups` argument)
# Create the plot
ggplot(g, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=instructor.name)) +
  geom_rect() +
  scale_fill_got(discrete = TRUE, option = "Margaery") +
  geom_label(x=4.5, aes(y=labelPosition, label=label), color="white", fontface = "bold", size=3) + # x here controls label position (inner / outer)
  #scale_color_brewer(palette=15) +
  coord_polar(theta="y") +
  xlim(c(0, 5)) +
  theme_void() +
  theme(legend.position = "none") +
  labs(title = "Percentage of Workouts by Instructor",
       caption = 'Source: @littlemissdata')

Favorite Instructors Month to Month

We can also create a 100% stacked bar chart with the breakdown in percentage of workouts by instructor and month.

g <- workouts_and_instructors %>%
  dplyr::filter(workout.fitness_discipline =='cycling') %>% 
  dplyr::filter(instructor.name !="NA") %>% 
  ggplot(aes(x=factor(workout.start_month))) +
  geom_bar(aes(fill = instructor.name), position = 'fill') +
  scale_fill_got(discrete = TRUE, option = "Margaery") +
  theme_light() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1), legend.position="bottom") +
  labs(title = "Percentage of Workouts by Instructor and Month",
       x = "Month", y = "Count",
       caption = 'Source: @littlemissdata') 
g

Density of Workouts per Day of Week and Hour Block

We can plot which days of week and hours of day we tend to work out. The steps below are pretty compact, but the logic is to create the necessary time/date columns with the mutate function, filter to only the columns needed with the select function, create a summary table of total workouts by hour and day with thegroup_by and summarize functions and then create a heatmap with ggplot and geom_tile.

col1 = "#ced4d6"
col2 = "#82B5C4"

workouts_and_instructors %>%
  mutate(workout.start_time_cst = with_tz(workout.start_timestamp,  tzone = "America/Chicago"),
         workout.start_day = wday(workout.start_time_cst, label = TRUE, abbr = FALSE,   week_start = getOption("lubridate.week.start", 1)),
         workout.start_hour = hour(workout.start_time_cst)) %>%
  select (workout.peloton.ride.description, workout.start_day, workout.start_hour) %>%
  group_by(workout.start_day, workout.start_hour) %>%
  dplyr::summarize(N = length(workout.peloton.ride.description)) %>%
  ggplot( aes(workout.start_hour, workout.start_day)) + geom_tile(aes(fill = N),colour = "white", na.rm = TRUE) +
  scale_fill_gradient(low = col1, high = col2) +
  guides(fill=guide_legend(title="Total Incidents")) +
  theme_bw() + theme_minimal() +
  labs(title = "Density of Workouts per Day of Week and Hour Block",
       x = "Hour Block", y = "Day of Week") +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = "none")
## `summarise()` regrouping output by 'workout.start_day' (override with `.groups` argument)

Other Ideas

If you’re trying to think about other cool ideas that you can do with this data, below are a few things which I thought could be neat to do:

Discover More

At the time of releasing the package, I realized there are a few other Peloton R packages out there. I haven’t had the chance to check them out yet but if you’re looking to round the bases on R Peloton packages, I encourage you to check give them a try. They both seem to have some interesting performance data!

Thank You

Thank you for trying out my pelotonR package! If you like the package, please share your results with me on twitter!