-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.Rmd
382 lines (250 loc) · 14.8 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
---
title: "Getting Started Guide for pelotonR"
author: "Laura Ellis"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<img src="logo.png" width="160px" align="right" />
# 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](https://app.swaggerhub.com/apis/DovOps/peloton-unofficial-api/0.2.3) which I used to familiarize myself with the API.
<br/>
The package offers a set of easy to use functions which allow the user to:
* Pull general Peloton data in a variety of formats
* Authenticate with the Peloton API
* Pull user specific data in a variety of formats when authenticated.
* Gather full data sets in one function call without having to handle paged API calls.
* Gather joined data sets in one function call.
# Load the Libraries
Before we start exploring the pelotonR package, we will load a few libraries used to help explore and display the data.
```{r echo=TRUE, message=TRUE}
#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
library(tidyverse) # For data munging
library(lubridate) # For dates
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`
```{r}
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`
```{r}
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`
```{r, max.height='100px'}
ride_info <- get_ride_info_list('55214456a1984c5885a087021e3f67b7')
#Nicely display data
list.tree(ride_info)
```
## 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
```{r paged.print=TRUE}
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`
```{r}
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`
```{r}
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.
```{r fig.width=10,fig.height=10}
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')
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`
```{r}
auth_response <-authenticate()
head(summary(auth_response))
```
# 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`
```{r}
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.
```{r fig.width=10,fig.height=5}
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`
```{r}
stats <-get_my_stats_list()
head(summary(stats))
```
## 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`
```{r}
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`
```{r}
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](https://github.com/aljrico/gameofthrones) by [Alejandro Jiménez](https://twitter.com/aljrico).
```{r fig.width=10,fig.height=5}
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')
p
```
#### Favorite Cycling Instructors Overall
Note that the code for creating this donut plot is from [r-graph-gallery.com](https://www.r-graph-gallery.com/128-ring-or-donut-plot.html).
```{r fig.width=10,fig.height=7}
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)
# 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.
```{r fig.width=10,fig.height=7}
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 the`group_by` and `summarize` functions and then create a heatmap with `ggplot` and `geom_tile`.
```{r fig.width=10,fig.height=5}
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")
```
# 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:
- It would be cool to do a [bar race animation chart](https://www.r-bloggers.com/how-to-create-bar-race-animation-charts-in-r/) to show your preferences over time.
- Most of the data sets have some image element (ie `workout.peloton.ride.image_url`and `instructor.instructor_hero_image_url`). I think it would be nice to do a graph with those images used. Possibly in a [scatter plot](https://stackoverflow.com/questions/2181902/how-to-use-an-image-as-a-point-in-ggplot), [or as a background](https://cran.r-project.org/web/packages/meme/vignettes/meme.html) or hopefully something even more creative.
- Add one of the many [giphy peloton stickers](https://giphy.com/search/peloton-stickers) to your graph with the magick package. [Tutorial here](https://www.littlemissdata.com/blog/lacroix)
- I think it would be great to start analyzing more performance based metrics. You could plot `workout.total_work`, `workout.total_video_watch_time_seconds`/`workout.peloton.ride.duration`, any of the difficulty measures or ride times and more.
- Perform a [tidy text](https://www.tidytextmining.com/) analysis on any of the ride or instructor description columns.
# 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!
- [bweiher/pelotonR](https://github.com/bweiher/pelotonR)
- [elliotpalmer/pelotonr](https://github.com/elliotpalmer/pelotonr)
# Thank You
Thank you for trying out my pelotonR package! If you like the package, please share your results with me on [twitter](https://twitter.com/littlemissdata)!