-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFull_Code_Markdown_File.Rmd
More file actions
2012 lines (1678 loc) · 87.8 KB
/
Full_Code_Markdown_File.Rmd
File metadata and controls
2012 lines (1678 loc) · 87.8 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Analysis of Smart Device Usage for Bellabeat Marketing Strategy"
author: "By Dane Tipene"
date: "`r format(Sys.Date(), '%B %d, %Y')`"
output:
html_document:
toc: true
toc_depth: 2
---
<script>
document.addEventListener("DOMContentLoaded", function() {
var buttons = document.getElementsByClassName("toggleButton");
var contents = document.getElementsByClassName("codeContent");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
var content = contents[i];
if (content.style.display === "none") {
content.style.display = "block";
this.innerText = "Hide " + this.innerText.substring(5);
} else {
content.style.display = "none";
this.innerText = "Show " + this.innerText.substring(5);
}
});
}
});
</script>
<div style="margin-top: 20px;"></div>
<br><br>
```{r bellabeat_logo, echo=FALSE, out.width='40%', out.height='40%'}
knitr::include_graphics(here::here("bellabeat_logo.png"))
```
[Bellabeat](https://bellabeat.com/), founded by Urska Srsen and Sando Mur, specializes in health-focused smart products designed to inform and inspire women. Since its inception in 2013, Bellabeat has rapidly grown and positioned itself as a leader in tech-driven wellness products for women.
<br><br>
# <span style="color: #FF8967;">Phase 1: Ask</span>
### Business Task
Analyze non-Bellabeat smart device usage data to gain insights that will enhance Bellabeat’s marketing strategy. Apply these insights to a selected Bellabeat product for targeted improvements.
### Key Stakeholders
- Urska Srsen: Bellabeat's cofounder and Chief Creative Officer
- Sando Mur: Bellabeat's cofounder and key member of executive team
- Bellabeat Marketing Team
### Market Insights
According to Fortune Business Insights, as well as studies and statistics from ValuePenguin (April 2022) and RunRepeat (October 2021), the following insights were observed:
- Market Growth: The global fitness tracker market is projected to grow from USD 53.94 billion in 2023 to USD 290.85 billion by 2032, at a CAGR of 21.3%.
- User Engagement: 92% of smartwatch wearers use their devices for health and fitness monitoring, with 88% claiming they helped in achieving fitness goals. Smartwatches hold the largest smart device type market share.
- Application: Running is the most common use, with 42.8% of users globally prioritizing this feature.
- Shipping Volume: 445 million wearable fitness devices were shipped, highlighting strong demand and market potential.
- Pandemic Impact: Fitness tracker shipments and revenue grew over 31% during the COVID-19 pandemic, indicating increased consumer interest in health.
- Gender: Women are nearly 40% more likely to use fitness trackers than men, benefiting female-focused brands like Bellabeat.
- For more detailed insights, you can refer to the full article [here.](https://www.fortunebusinessinsights.com/fitness-tracker-market-103358)
<br><br>
<br><br>
# <span style="color: #FF8967;">Phase 2: Prepare</span>
### Data Source
- Fitabase dataset made available through Kaggle user [Mobius](https://www.kaggle.com/datasets/arashnic/fitbit) and licensed under CC0: Public Domain
- Dataset generated from 33 eligible Fitbit user logs from smart devices
- Acknowledgements - Robert Furger, Julia Brinton, Michael Keating, Alexa Ortiz
### Data Credibility
The data is reliable but dated, originating from 2016 and collected over 31 days from 33 participants.
The small sample size of 33 participants reduces the confidence level of the derived insights. Additionally, the absence of demographic information such as gender, age, and location makes it highly unlikely to determine if the data accurately represents the population. This also hinders the identification of female-specific trends.
### Chosen Tools
I initially examined the datasets in Excel to sort and filter the data. However, the 'Minute' datasets contained millions of rows, making it impractical to manage in Excel. Therefore, I loaded all the data into R Studio for more efficient cleaning and analysis.
- Excel
- R
- R Packages
<button class="toggleButton">Show Package Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r installed_packages, eval=FALSE, results='hide', message=FALSE}
install.packages("tidyverse")
install.packages("lubridate")
install.packages("janitor")
install.packages("readxl")
install.packages("data.table")
```
```{r load_packages, eval=TRUE, message=FALSE, warning=FALSE}
library(tidyverse)
library(lubridate)
library(janitor)
library(readxl)
library(data.table)
```
</code></pre>
</div>
### Chosen Datasets
- dailyActivity_merged
- dailyCalories_merged
- dailyIntensities_merged
- dailySteps_merged
- heartrate_seconds_merged
- hourlyCalories_merged
- hourlyIntensities_merged
- hourlySteps_merged
- minuteintensitiesNarrow_merged
- minutesSleep_merged
- sleepDay_merged
- weightLogInfo_merged
<button class="toggleButton">Show Loaded CSV Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r loaded_csv_files, eval=TRUE}
daily_activity <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/dailyActivity_merged.csv")
daily_calories <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/dailyCalories_merged.csv")
daily_intensities <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/dailyIntensities_merged.csv")
daily_steps <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/dailySteps_merged.csv")
hourly_calories <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/hourlyCalories_merged.csv")
hourly_intensities <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/hourlyIntensities_merged.csv")
hourly_steps <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/hourlySteps_merged.csv")
minute_sleep <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/minuteSleep_merged.csv")
sleep_day <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/sleepDay_merged.csv")
weight_log <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/weightLogInfo_merged.csv")
```
```{r loaded_separately, eval=TRUE}
# Load separately to avoid crash
heartrate_seconds <- read.csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/heartrate_seconds_merged.csv")
```
```{r loaded_separately2, eval=TRUE}
# Load separately to avoid crash
minute_intensities <- read_csv("mturkfitbit_export_4.12.16-5.12.16/Fitabase Data 4.12.16-5.12.16/minuteIntensitiesNarrow_merged.csv")
```
</code></pre>
</div>
<br><br>
# <span style="color: #FF8967;">Phase 3: Process</span>
## Cleaning Log
#### Inspect and Preview All Datasets
- Inspected Data using 'str()' function
- Searched for matching columns for potential merging, and checked for inconsistencies in column names and formats
- Found "Id", "ActivityDate", and "ActivityHour" columns suitable for merging separate daily and hourly datasets
<button class="toggleButton">Show Data Inspection Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r data_inspection, eval=TRUE}
# Look for matching columns, inconsistencies in column names and in column formats
str(daily_activity)
str(daily_calories)
str(daily_intensities)
str(daily_steps)
str(heartrate_seconds)
str(hourly_calories)
str(hourly_intensities)
str(hourly_steps)
str(minute_intensities)
str(minute_sleep)
str(sleep_day)
str(weight_log)
```
</code></pre>
</div>
#### Dataset Transformations
- Cleaned inconsistent column names to match appropriate datasets
- Renamed date/time columns to either "ActivityDate", "ActivityMinutes", or "ActivitySeconds"
- Renamed ‘daily_activity’/“TotalSteps” to “StepTotal” to align with other 'steps' datasets
- Standardized inconsistent date/time formats
- A total of 33 participants were identified, which is 3 more than originally stated in the dataset description.
- Identified 65 missing values in the 'weight_log' dataset and chose not to delete these rows, as it would remove 99% of the data
- Identified and removed 3 duplicates from the 'sleep_day' dataset
- Identified and removed 543 duplicates from the 'minute_sleep' dataset
- Found the 'minute_sleep' dataset to be of no value and excluded it from the analysis
- Merged Daily datasets together
- Merged Hourly datasets together
- Reduced datasets from 12 to 5: two merged datasets ('daily_combined' and 'hourly_combined') and three separate datasets ('minute_intensities', 'heartrate_seconds' and 'weight_log')
<button class="toggleButton">Show Column Transformation Code Details</button>
<br><br>
<div class="codeContent" style="display:none;">
</code></pre>
```{r column_transformation, eval=TRUE}
# Rename columns to ensure consistency and match 'daily_activity' dataset
colnames(daily_activity)[colnames(daily_activity) == "TotalSteps"] <- "StepTotal"
colnames(daily_calories)[colnames(daily_calories) == "ActivityDay"] <- "ActivityDate"
colnames(daily_intensities)[colnames(daily_intensities) == "ActivityDay"] <- "ActivityDate"
colnames(daily_steps)[colnames(daily_steps) == "ActivityDay"] <- "ActivityDate"
colnames(heartrate_seconds)[colnames(heartrate_seconds) == "Time"] <- "ActivitySeconds"
colnames(heartrate_seconds)[colnames(heartrate_seconds) == "Value"] <- "Bpm"
colnames(sleep_day)[colnames(sleep_day) == "SleepDay"] <- "ActivityDate"
colnames(minute_intensities)[colnames(minute_intensities) == "ActivityMinute"] <- "ActivityMinutes"
colnames(minute_sleep)[colnames(minute_sleep) == "date"] <- "ActivityMinutes"
colnames(weight_log)[colnames(weight_log) == "Date"] <- "ActivityDate"
# Ensure date columns are in the same format
daily_activity$ActivityDate <- as.Date(daily_activity$ActivityDate, format="%m/%d/%Y")
daily_calories$ActivityDate <- as.Date(daily_calories$ActivityDate, format="%m/%d/%Y")
daily_intensities$ActivityDate <- as.Date(daily_intensities$ActivityDate, format="%m/%d/%Y")
daily_steps$ActivityDate <- as.Date(daily_steps$ActivityDate, format="%m/%d/%Y")
heartrate_seconds$ActivitySeconds <- as.POSIXct(heartrate_seconds$ActivitySeconds, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
hourly_calories$ActivityHour <- as.POSIXct(hourly_calories$ActivityHour, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
hourly_intensities$ActivityHour <- as.POSIXct(hourly_intensities$ActivityHour, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
hourly_steps$ActivityHour <- as.POSIXct(hourly_steps$ActivityHour, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
sleep_day$ActivityDate <- as.Date(sleep_day$ActivityDate, format="%m/%d/%Y")
minute_intensities$ActivityMinutes <- as.POSIXct(minute_intensities$ActivityMinutes, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
minute_sleep$ActivityMinutes <- as.POSIXct(minute_sleep$ActivityMinutes, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
weight_log$ActivityDate <- as.POSIXct(weight_log$ActivityDate, format="%m/%d/%Y %I:%M:%S %p", tz=Sys.timezone())
# Confirm changes in final inspection
str(daily_activity)
str(daily_calories)
str(daily_intensities)
str(daily_steps)
str(heartrate_seconds)
str(hourly_calories)
str(hourly_intensities)
str(hourly_steps)
str(minute_intensities)
str(minute_sleep)
str(sleep_day)
str(weight_log)
```
</code></pre>
</div>
<button class="toggleButton">Show Missing Value Code Details</button>
<br><br>
<div class="codeContent" style="display:none;">
</code></pre>
```{r missing_values, eval=TRUE}
# Identify missing values
# List of datasets
datasets <- list(
daily_activity = daily_activity,
daily_calories = daily_calories,
daily_intensities = daily_intensities,
daily_steps = daily_steps,
heartrate_seconds = heartrate_seconds,
hourly_calories = hourly_calories,
hourly_intensities = hourly_intensities,
hourly_steps = hourly_steps,
minute_intensities = minute_intensities,
minute_sleep = minute_sleep,
sleep_day = sleep_day,
weight_log = weight_log
)
# Check for missing values in each dataset
for (name in names(datasets)) {
cat("\nChecking for missing values in:", name, "\n")
print(sapply(datasets[[name]], function(x) sum(is.na(x))))
}
```
</code></pre>
</div>
<button class="toggleButton">Show Duplicates Code Details</button>
<br><br>
<div class="codeContent" style="display:none;">
</code></pre>
```{r duplicate_rows, eval=TRUE}
# Looking for duplicate rows
# List of datasets
datasets <- list(
daily_activity = daily_activity,
daily_calories = daily_calories,
daily_intensities = daily_intensities,
daily_steps = daily_steps,
hourly_calories = hourly_calories,
hourly_intensities = hourly_intensities,
hourly_steps = hourly_steps,
minute_intensities = minute_intensities,
minute_sleep = minute_sleep,
sleep_day = sleep_day,
weight_log = weight_log
)
# Check for duplicate rows in each dataset
for (name in names(datasets)) {
cat("\nChecking for duplicate rows in:", name, "\n")
duplicates <- sum(duplicated(datasets[[name]]))
cat("Number of duplicate rows:", duplicates, "\n")
}
```
```{r sleep_day_duplicates, eval=FALSE}
# Found 3 duplicates in 'sleep_day'
# Identify duplicates
duplicates <- sleep_day[duplicated(sleep_day) | duplicated(sleep_day, fromLast = TRUE), ]
# Print the duplicate rows to confirm removal
print(duplicates)
# Remove duplicate rows, keeping only the first occurrence
sleep_day <- sleep_day[!duplicated(sleep_day), ]
```
```{r minute_sleep_duplicates, eval=FALSE}
# Found 543 duplicates in 'minute_sleep'
# Identify duplicates
duplicates <- minute_sleep[duplicated(minute_sleep) | duplicated(minute_sleep, fromLast = TRUE), ]
# Print the duplicate rows to confirm removal
print(duplicates)
# Remove duplicate rows, keeping only the first occurrence
minute_sleep <- minute_sleep[!duplicated(minute_sleep), ]
```
</code></pre>
</div>
<button class="toggleButton">Show Heartrate Duplicates Code Details</button>
<br><br>
<div class="codeContent" style="display:none;">
</code></pre>
```{r heartrate_seconds_duplicates, eval=TRUE}
# Running heart rate_seconds investigation separately to reduce likely hood of crash
# Created a function to process and remove duplicates in chunks
count_duplicates_in_chunks <- function(data, chunk_size = 100000) {
num_chunks <- ceiling(nrow(data) / chunk_size)
total_duplicates <- 0
for (i in 1:num_chunks) {
chunk <- data[((i - 1) * chunk_size + 1):min(i * chunk_size, nrow(data)), ]
total_duplicates <- total_duplicates + sum(duplicated(chunk))
}
return(total_duplicates)
}
# Convert heart rate_seconds to data.table
heartrate_seconds_dt <- as.data.table(heartrate_seconds)
# Count duplicates using chunk processing
num_duplicates <- count_duplicates_in_chunks(heartrate_seconds_dt)
# Print the number of duplicates
cat("Number of duplicate rows in heartrate_seconds:", num_duplicates, "\n")
```
</code></pre>
</div>
<button class="toggleButton">Show Dataset Merge Code Details</button>
<br><br>
<div class="codeContent" style="display:none;">
</code></pre>
```{r merging_datasets, eval=TRUE, message=FALSE, warning=FALSE}
# Merge multiple datasets (daily_activity, daily_intensities, daily_calories, daily_steps, sleep_day) into single dataset named 'daily_combined' using common columns "Id" and "ActivityDate"
# Removes any duplicate columns that have a ".y" suffix, ensuring only the original columns are retained in the daily_combined dataset.
daily_combined <- daily_activity %>%
left_join(daily_intensities, by = c("Id", "ActivityDate")) %>%
left_join(daily_calories, by = c("Id", "ActivityDate")) %>%
left_join(daily_steps, by = c("Id", "ActivityDate")) %>%
left_join(sleep_day, by = c("Id", "ActivityDate")) %>%
select(-contains(".y"))
# Remove ".x" suffix from column names
colnames(daily_combined) <- gsub("\\.x$", "", colnames(daily_combined))
# Merge hourly datasets using common columns "Id" and "ActivityHour" and named 'hourly_combined'
# Remove any duplicate columns that have a ".y" suffix, ensuring only the original columns are retained in the hourly_combined dataset.
hourly_combined <- hourly_calories %>%
left_join(hourly_intensities, by = c("Id", "ActivityHour")) %>%
left_join(hourly_steps, by = c("Id", "ActivityHour")) %>%
select(-contains(".y"))
```
</code></pre>
</div>
<br><br>
# <span style="color: #FF8967;">Phase 4: Analysis and Insights</span>
## User Engagement Patterns
```{r calculate_number_of_unique_users_per_metric, echo=FALSE, eval=TRUE}
# Calculate unique users for physical activity
activity_users <- daily_combined %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Physical Activity")
# Calculate unique users for heart rate
heartrate_users <- heartrate_seconds %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Heart Rate")
# Calculate unique users for sleep
sleep_users <- sleep_day %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Sleep")
# Calculate unique users for weight
weight_users <- weight_log %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Weight")
# Combine all user data into a single dataframe
user_data <- bind_rows(activity_users, heartrate_users, sleep_users, weight_users)
# Calculate percentages
total_users <- 33 # Total number of users
user_data <- user_data %>%
mutate(Percentage = (Users / total_users) * 100)
```
```{r create_the_horizontal_bar_chart, echo=FALSE, results='hide', message=FALSE, fig.width=5, fig.height=3, fig.show='hold'}
# Create the horizontal bar chart with custom colors and annotations
ggplot(user_data, aes(x = Percentage, y = Metric, fill = Metric)) +
geom_bar(stat = "identity", color = "lightgrey") +
scale_fill_manual(values = c("Physical Activity" = "#ff6666",
"Heart Rate" = "#ffb6b9",
"Sleep" = "#FF8967",
"Weight" = "#ffe6e6")) +
geom_text(aes(label = paste0(round(Percentage, 1), "%")),
position = position_stack(vjust = 0.5),
color = "black",
size = 3) +
theme_minimal() +
labs(title = "Percentage of Users Tracking Each Metric",
x = "Percentage of Users",
y = "Metric Type") +
scale_x_continuous(labels = scales::percent_format(scale = 1)) +
theme(legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin = margin(t = 20, r = 10, b = 10, l = 10, unit = "pt"))
```
- The data measures four primary metrics: Physical Activity, Sleep, Heart Rate, and Weight.
- Among these metrics, users clearly valued tracking their physical activity the most, while weight and heart rate were tracked the least. This could be an opportunity to investigate why these metrics are less tracked and how to encourage more users.
<button class="toggleButton">Show Graph Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r toggle_calculate_number_of_unique_users_per_metric, eval=FALSE}
# Calculate unique users for physical activity
activity_users <- daily_combined %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Physical Activity")
# Calculate unique users for heart rate
heartrate_users <- heartrate_seconds %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Heart Rate")
# Calculate unique users for sleep
sleep_users <- sleep_day %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Sleep")
# Calculate unique users for weight
weight_users <- weight_log %>%
summarise(Users = n_distinct(Id)) %>%
mutate(Metric = "Weight")
# Combine all user data into a single dataframe
user_data <- bind_rows(activity_users, heartrate_users, sleep_users, weight_users)
# Calculate percentages
total_users <- 33 # Total number of users
user_data <- user_data %>%
mutate(Percentage = (Users / total_users) * 100)
# Create the horizontal bar chart with custom colors and annotations
ggplot(user_data, aes(x = Percentage, y = Metric, fill = Metric)) +
geom_bar(stat = "identity", color = "lightgrey") +
scale_fill_manual(values = c("Physical Activity" = "#ff6666",
"Heart Rate" = "#ffb6b9",
"Sleep" = "#FF8967",
"Weight" = "#ffe6e6")) +
geom_text(aes(label = paste0(round(Percentage, 1), "%")),
position = position_stack(vjust = 0.5),
color = "black",
size = 3) +
theme_minimal() +
labs(title = "Percentage of Users Tracking Each Metric",
x = "Percentage of Users",
y = "Metric Type") +
scale_x_continuous(labels = scales::percent_format(scale = 1)) +
theme(legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin = margin(t = 20, r = 10, b = 10, l = 10, unit = "pt"))
```
</code></pre>
</div>
<br><br>
```{r usage_rate_of_participants, echo=FALSE, results='hide', message=FALSE, fig.width=5, fig.height=3, fig.show='hold'}
# Calculate the number of unique days each user has recorded data
user_days <- daily_combined %>%
group_by(Id) %>%
summarise(NumberOfDays = n_distinct(ActivityDate))
# Categorize users based on the number of days they recorded data
user_days <- user_days %>%
mutate(UsageCategory = case_when(
NumberOfDays >= 1 & NumberOfDays <= 10 ~ "Minimal Use 1-10 Days",
NumberOfDays >= 11 & NumberOfDays <= 20 ~ "Moderate Use 11-20 Days",
NumberOfDays >= 21 & NumberOfDays <= 31 ~ "Consistent Use 21-31 Days"
))
# Adjust the order of the UsageCategory factor levels
user_days <- user_days %>%
mutate(UsageCategory = factor(UsageCategory, levels = c("Consistent Use 21-31 Days", "Moderate Use 11-20 Days", "Minimal Use 1-10 Days")))
# Create a summary dataset for the pie chart
usage_summary <- user_days %>%
count(UsageCategory) %>%
mutate(Percentage = (n / sum(n)) * 100)
# Calculate label positions
usage_summary <- usage_summary %>%
arrange(desc(UsageCategory)) %>%
mutate(ypos = cumsum(Percentage) - 0.5 * Percentage)
# Create the pie chart with outside annotations
ggplot(usage_summary, aes(x = "", y = Percentage, fill = UsageCategory)) +
geom_bar(width = 1, stat = "identity", color = "lightgrey") +
coord_polar(theta = "y") +
scale_fill_manual(values = c("Minimal Use 1-10 Days" = "#fff5f5",
"Moderate Use 11-20 Days" = "#ffd9d9",
"Consistent Use 21-31 Days" = "#FF8967")) +
geom_text(aes(y = ypos, label = paste0(round(Percentage, 2), "%")),
color = "black",
size = 3.5,
nudge_x = 0.7) + # Adjust position to place labels outside
labs(title = "Usage Rate of Participants",
x = "",
y = "") +
theme_minimal() +
theme(axis.text.x = element_blank(), # Remove x-axis text
axis.ticks = element_blank(), # Remove axis ticks
panel.grid = element_blank(), # Remove grid lines
axis.title.x = element_blank(), # Remove x-axis title
axis.title.y = element_blank()) # Remove y-axis title
```
- The high percentage of "Consistent Use" participants suggests that the device/platform is highly effective in engaging users regularly. This provides a solid foundation for both marketing the product and developing new features.
- At the same time, the presence of "Moderate Use" and "Minimal Use" users indicates an opportunity to further refine and personalize the user experience to increase engagement across the board.
<button class="toggleButton">Show Graph Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r toggle_usage_rate_of_participants, eval=FALSE}
# Calculate the number of unique days each user has recorded data
user_days <- daily_combined %>%
group_by(Id) %>%
summarise(NumberOfDays = n_distinct(ActivityDate))
# Categorize users based on the number of days they recorded data
user_days <- user_days %>%
mutate(UsageCategory = case_when(
NumberOfDays >= 1 & NumberOfDays <= 10 ~ "Minimal Use 1-10 Days",
NumberOfDays >= 11 & NumberOfDays <= 20 ~ "Moderate Use 11-20 Days",
NumberOfDays >= 21 & NumberOfDays <= 31 ~ "Consistent Use 21-31 Days"
))
# Adjust the order of the UsageCategory factor levels
user_days <- user_days %>%
mutate(UsageCategory = factor(UsageCategory, levels = c("Consistent Use 21-31 Days", "Moderate Use 11-20 Days", "Minimal Use 1-10 Days")))
# Create a summary dataset for the pie chart
usage_summary <- user_days %>%
count(UsageCategory) %>%
mutate(Percentage = (n / sum(n)) * 100)
# Calculate label positions
usage_summary <- usage_summary %>%
arrange(desc(UsageCategory)) %>%
mutate(ypos = cumsum(Percentage) - 0.5 * Percentage)
# Create the pie chart with outside annotations
ggplot(usage_summary, aes(x = "", y = Percentage, fill = UsageCategory)) +
geom_bar(width = 1, stat = "identity", color = "lightgrey") +
coord_polar(theta = "y") +
scale_fill_manual(values = c("Minimal Use 1-10 Days" = "#fff5f5",
"Moderate Use 11-20 Days" = "#ffd9d9",
"Consistent Use 21-31 Days" = "#FF8967")) +
geom_text(aes(y = ypos, label = paste0(round(Percentage, 2), "%")),
color = "black",
size = 3.5,
nudge_x = 0.7) + # Adjust position to place labels outside
labs(title = "Usage Rate of Participants",
x = "",
y = "") +
theme_minimal() +
theme(axis.text.x = element_blank(), # Remove x-axis text
axis.ticks = element_blank(), # Remove axis ticks
panel.grid = element_blank(), # Remove grid lines
axis.title.x = element_blank(), # Remove x-axis title
axis.title.y = element_blank()) # Remove y-axis title
```
</code></pre>
</div>
<br><br>
```{r average_daily_device_usage, eval=TRUE, echo=FALSE}
# Calculate the number of unique days each user has recorded data
user_days <- daily_combined %>%
group_by(Id) %>%
summarise(NumberOfDays = n_distinct(ActivityDate))
# Calculate the average, minimum, and maximum number of days across all users
summary_days <- user_days %>%
summarise(
AverageDays = mean(NumberOfDays, na.rm = TRUE),
MinDays = min(NumberOfDays, na.rm = TRUE),
MaxDays = max(NumberOfDays, na.rm = TRUE)
)
# Add the percentage column to the summary_days tibble
summary_days <- summary_days %>%
mutate(PercentageOfTotalDays = (AverageDays / 31) * 100)
# Print the updated summary statistics
print(summary_days)
```
- The average daily usage of their smart devices was measured at 28.5 days out of 31, indicating that participants used their devices 91.9% of the time.
- Only one user used their device for 4 days, while the next closest participant used their device for 16 days.
<button class="toggleButton">Show Tibble Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r toggle_average_daily_device_usage, eval=FALSE}
# Calculate the number of unique days each user has recorded data
user_days <- daily_combined %>%
group_by(Id) %>%
summarise(NumberOfDays = n_distinct(ActivityDate))
# Calculate the average, minimum, and maximum number of days across all users
summary_days <- user_days %>%
summarise(
AverageDays = mean(NumberOfDays, na.rm = TRUE),
MinDays = min(NumberOfDays, na.rm = TRUE),
MaxDays = max(NumberOfDays, na.rm = TRUE)
)
# Add the percentage column to the summary_days tibble
summary_days <- summary_days %>%
mutate(PercentageOfTotalDays = (AverageDays / 31) * 100)
# Print the updated summary statistics
print(summary_days)
```
</code></pre>
</div>
<br><br>
<br><br>
## Activity Level Categories
- Fitabase categorizes activity levels into four groups: Sedentary, Lightly Active, Fairly Active, and Very Active.
- According to this [LiveStrong](https://www.livestrong.com/article/401892-what-are-sedentary-moderate-high-activity-exercise-levels/) article, the "10,000 Steps Project" suggests five levels of activity. I combined the last two levels into the Very Active category (10,000 steps and above). By averaging the Daily Total Steps measured for each participant, I was able to categorize each participant into their respective Activity Level.<br><br>
```{r caterized_graphs_1, echo=FALSE, results='hide', message=FALSE, fig.width=5, fig.height=3, fig.show='hold'}
# Calculate the average for each column for each unique Id
avg_daily_combined <- daily_combined %>%
group_by(Id) %>%
summarise(
AvgStepTotal = mean(StepTotal, na.rm = TRUE),
AvgTotalDistance = mean(TotalDistance, na.rm = TRUE),
AvgVeryActiveMinutes = mean(VeryActiveMinutes, na.rm = TRUE),
AvgFairlyActiveMinutes = mean(FairlyActiveMinutes, na.rm = TRUE),
AvgLightlyActiveMinutes = mean(LightlyActiveMinutes, na.rm = TRUE),
AvgSedentaryMinutes = mean(SedentaryMinutes, na.rm = TRUE),
AvgCalories = mean(Calories, na.rm = TRUE),
AvgTotalMinutesAsleep = mean(TotalMinutesAsleep, na.rm = TRUE),
AvgTotalTimeInBed = mean(TotalTimeInBed, na.rm = TRUE)
)
# Group users into categories based on the adjusted 'AvgStepTotal' definitions
categorized_data <- avg_daily_combined %>%
mutate(
ActivityCategory = case_when(
AvgStepTotal < 5000 ~ "Sedentary",
AvgStepTotal >= 5000 & AvgStepTotal <= 7499 ~ "LightlyActive",
AvgStepTotal >= 7500 & AvgStepTotal <= 9999 ~ "FairlyActive",
AvgStepTotal >= 10000 ~ "VeryActive"
)
)
# Ensure the categories are ordered correctly
categorized_data$ActivityCategory <- factor(categorized_data$ActivityCategory,
levels = c("Sedentary", "LightlyActive", "FairlyActive", "VeryActive"))
# Create a summary dataset for the pie chart
pie_data <- categorized_data %>%
count(ActivityCategory) %>%
mutate(Percentage = n / sum(n) * 100)
# Define the custom colors
custom_colors <- c("Sedentary" = "#fff5f5",
"LightlyActive" = "#ffd9d9",
"FairlyActive" = "#FF8967",
"VeryActive" = "#ff6666")
# Create the pie chart
ggplot(pie_data, aes(x = "", y = Percentage, fill = ActivityCategory)) +
geom_bar(width = 1, stat = "identity", color = "lightgrey") +
coord_polar(theta = "y") +
scale_fill_manual(values = custom_colors) +
geom_text(aes(label = paste0(round(Percentage, 2), "%")),
position = position_stack(vjust = 0.5),
color = "black",
size = 3) +
labs(title = "Percentage of Users per Activity Category") +
theme_minimal() +
theme(axis.text.x = element_blank(), # Remove x-axis text
axis.ticks = element_blank(), # Remove axis ticks
panel.grid = element_blank(), # Remove grid lines
axis.title.x = element_blank(), # Remove x-axis title
axis.title.y = element_blank()) # Remove y-axis title
```
#### Even Distribution
- The distribution across categories is relatively even, with no single category dominating the user base.
- This suggests that users have varied levels of activity, and the platform caters to a diverse group of individuals with different activity levels.<br><br>
#### Middle Range Dominance
- The middle categories (Lightly Active and Fairly Active) each account for 27.3% of users.
- This indicates that most users fall into moderate activity levels, which could be targeted for further engagement and improvement.<br><br>
#### Opportunities for Engagement
- Users in the Sedentary category could be targeted with personalized interventions and encouragement to increase their activity levels. Reward systems could be utilized to encourage movement.
- Users in the Very Active category might be interested in advanced features or challenges to maintain their high activity levels.
<button class="toggleButton">Show Graph Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r toggle_categorized_graphs_1, eval=FALSE}
# Calculate the average for each column for each unique Id
avg_daily_combined <- daily_combined %>%
group_by(Id) %>%
summarise(
AvgStepTotal = mean(StepTotal, na.rm = TRUE),
AvgTotalDistance = mean(TotalDistance, na.rm = TRUE),
AvgVeryActiveMinutes = mean(VeryActiveMinutes, na.rm = TRUE),
AvgFairlyActiveMinutes = mean(FairlyActiveMinutes, na.rm = TRUE),
AvgLightlyActiveMinutes = mean(LightlyActiveMinutes, na.rm = TRUE),
AvgSedentaryMinutes = mean(SedentaryMinutes, na.rm = TRUE),
AvgCalories = mean(Calories, na.rm = TRUE),
AvgTotalMinutesAsleep = mean(TotalMinutesAsleep, na.rm = TRUE),
AvgTotalTimeInBed = mean(TotalTimeInBed, na.rm = TRUE)
)
# Group users into categories based on the adjusted 'AvgStepTotal' definitions
categorized_data <- avg_daily_combined %>%
mutate(
ActivityCategory = case_when(
AvgStepTotal < 5000 ~ "Sedentary",
AvgStepTotal >= 5000 & AvgStepTotal <= 7499 ~ "LightlyActive",
AvgStepTotal >= 7500 & AvgStepTotal <= 9999 ~ "FairlyActive",
AvgStepTotal >= 10000 ~ "VeryActive"
)
)
# Ensure the categories are ordered correctly
categorized_data$ActivityCategory <- factor(categorized_data$ActivityCategory,
levels = c("Sedentary", "LightlyActive", "FairlyActive", "VeryActive"))
# Create a summary dataset for the pie chart
pie_data <- categorized_data %>%
count(ActivityCategory) %>%
mutate(Percentage = n / sum(n) * 100)
# Define the custom colors
custom_colors <- c("Sedentary" = "#fff5f5",
"LightlyActive" = "#ffd9d9",
"FairlyActive" = "#FF8967",
"VeryActive" = "#ff6666")
# Create the pie chart
ggplot(pie_data, aes(x = "", y = Percentage, fill = ActivityCategory)) +
geom_bar(width = 1, stat = "identity", color = "lightgrey") +
coord_polar(theta = "y") +
scale_fill_manual(values = custom_colors) +
geom_text(aes(label = paste0(round(Percentage, 2), "%")),
position = position_stack(vjust = 0.5),
color = "black",
size = 3) +
labs(title = "Percentage of Users per Activity Category") +
theme_minimal() +
theme(axis.text.x = element_blank(), # Remove x-axis text
axis.ticks = element_blank(), # Remove axis ticks
panel.grid = element_blank(), # Remove grid lines
axis.title.x = element_blank(), # Remove x-axis title
axis.title.y = element_blank()) # Remove y-axis title
```
</code></pre>
</div>
<br><br>
### Time Distribution Across Activity Levels
```{r time_distribution_data_creation, eval=TRUE, echo=FALSE}
# Convert to data.table
setDT(minute_intensities)
# Get the range of numbers in the Intensity column
intensity_range <- minute_intensities[, .(min_intensity = min(Intensity, na.rm = TRUE),
max_intensity = max(Intensity, na.rm = TRUE))]
# Categorize activity levels
minute_intensities[, ActivityLevel := fifelse(Intensity == 0, "Sedentary",
fifelse(Intensity == 1, "LightlyActive",
fifelse(Intensity == 2, "FairlyActive",
fifelse(Intensity == 3, "VeryActive", "Other"))))]
# Extract date from ActivityMinutes column
minute_intensities[, Date := as.Date(ActivityMinutes)]
# Calculate the amount of minutes spent in each ActivityLevel per user per day
daily_activity_levels <- minute_intensities[, .(MinutesSpent = .N), by = .(Id, Date, ActivityLevel)]
# Calculate the total minutes spent per user per day
total_minutes_per_day <- daily_activity_levels[, .(TotalMinutesSpent = sum(MinutesSpent, na.rm = TRUE)), by = .(Id, Date)]
# Merge to get the percentage of minutes spent in each activity level
daily_activity_levels <- merge(daily_activity_levels, total_minutes_per_day, by = c("Id", "Date"))
daily_activity_levels[, Percentage := (MinutesSpent / TotalMinutesSpent) * 100]
# Calculate the average percentage per activity level
average_percentage_per_level <- daily_activity_levels[, .(AvgPercentage = mean(Percentage, na.rm = TRUE)), by = .(Id, ActivityLevel)]
# Calculate average minutes spent per activity level per user
average_minutes_per_level <- daily_activity_levels[, .(AvgMinutesSpent = mean(MinutesSpent, na.rm = TRUE)), by = .(Id, ActivityLevel)]
# Merge average percentage back to the average_minutes_per_level dataset
average_minutes_per_level <- merge(average_minutes_per_level, average_percentage_per_level, by = c("Id", "ActivityLevel"))
# Add a column to convert minutes to hours
average_minutes_per_level[, AvgHoursSpent := AvgMinutesSpent / 60]
# Summarize the total average minutes spent, average percentage, and average hours spent for each activity level
summary_table <- average_minutes_per_level[, .(
TotalAvgMinutesSpent = sum(AvgMinutesSpent, na.rm = TRUE),
TotalAvgPercentage = mean(AvgPercentage, na.rm = TRUE),
TotalAvgHoursSpent = sum(AvgHoursSpent, na.rm = TRUE)
), by = ActivityLevel]
# Ensure the total average percentage for each activity level
summary_table <- summary_table[, .(
ActivityLevel,
TotalAvgMinutesSpent,
TotalAvgPercentage,
TotalAvgHoursSpent
)]
```
```{r percentage_of_time_per_activity_level, echo=FALSE, results='hide', message=FALSE, fig.width=5, fig.height=3, fig.show='hold'}
# Define custom colors for the Activity Levels
activity_colors <- c(
"Sedentary" = "#fff5f5",
"LightlyActive" = "#ffd9d9",
"FairlyActive" = "#FF8967",
"VeryActive" = "#FF6666"
)
# Create labels for the legend
summary_table[, legend_label := paste0(ActivityLevel, " (", round(TotalAvgPercentage, 2), "%)")]
# Create the pie chart using ggplot2
ggplot(summary_table, aes(x = "", y = TotalAvgPercentage, fill = ActivityLevel)) +
geom_bar(width = 1, stat = "identity", color = "lightgrey") +
coord_polar(theta = "y") +
scale_fill_manual(values = activity_colors, labels = summary_table$legend_label) +
labs(title = "Percentage of Time Spent in Each Activity Level") +
theme_minimal() +
theme(
axis.text.x = element_blank(), # Remove x-axis text
axis.ticks = element_blank(), # Remove axis ticks
panel.grid = element_blank(), # Remove grid lines
axis.title.x = element_blank(), # Remove x-axis title
axis.title.y = element_blank(), # Remove y-axis title
legend.position = "right" # Position legend to the right
) +
guides(fill = guide_legend(title = "Activity Level"))
```
- The majority of each day is spent at the sedentary level, accounting for 84.1% or 19 hours and 49 minutes.
- This is approximately composed of 7 hours in bed, likely 8-10 hours of working and commuting, and possibly an hour or two of watching TV.
- Lightly Active time accounts for 14% or 3 hours and 25 minutes, likely spent on routine daily tasks.
- Very Active time is 1.97% or 28 minutes, potentially spent on vigorous exercise.
- Lastly, 1.43%, or 20 minutes, is spent in the Fairly Active category, which could also involve exercise.
<button class="toggleButton">Show Graph Code Details</button>
<div class="codeContent" style="display:none;">
</code></pre>
```{r toggle_time_distribution, eval=FALSE}
# Convert to data.table
setDT(minute_intensities)
# Get the range of numbers in the Intensity column
intensity_range <- minute_intensities[, .(min_intensity = min(Intensity, na.rm = TRUE),
max_intensity = max(Intensity, na.rm = TRUE))]
# Categorize activity levels
minute_intensities[, ActivityLevel := fifelse(Intensity == 0, "Sedentary",
fifelse(Intensity == 1, "LightlyActive",
fifelse(Intensity == 2, "FairlyActive",
fifelse(Intensity == 3, "VeryActive", "Other"))))]
# Extract date from ActivityMinutes column
minute_intensities[, Date := as.Date(ActivityMinutes)]
# Calculate the amount of minutes spent in each ActivityLevel per user per day
daily_activity_levels <- minute_intensities[, .(MinutesSpent = .N), by = .(Id, Date, ActivityLevel)]
# Calculate the total minutes spent per user per day
total_minutes_per_day <- daily_activity_levels[, .(TotalMinutesSpent = sum(MinutesSpent, na.rm = TRUE)), by = .(Id, Date)]
# Merge to get the percentage of minutes spent in each activity level
daily_activity_levels <- merge(daily_activity_levels, total_minutes_per_day, by = c("Id", "Date"))
daily_activity_levels[, Percentage := (MinutesSpent / TotalMinutesSpent) * 100]
# Calculate the average percentage per activity level
average_percentage_per_level <- daily_activity_levels[, .(AvgPercentage = mean(Percentage, na.rm = TRUE)), by = .(Id, ActivityLevel)]
# Calculate average minutes spent per activity level per user
average_minutes_per_level <- daily_activity_levels[, .(AvgMinutesSpent = mean(MinutesSpent, na.rm = TRUE)), by = .(Id, ActivityLevel)]
# Merge average percentage back to the average_minutes_per_level dataset
average_minutes_per_level <- merge(average_minutes_per_level, average_percentage_per_level, by = c("Id", "ActivityLevel"))
# Add a column to convert minutes to hours
average_minutes_per_level[, AvgHoursSpent := AvgMinutesSpent / 60]
# Summarize the total average minutes spent, average percentage, and average hours spent for each activity level
summary_table <- average_minutes_per_level[, .(
TotalAvgMinutesSpent = sum(AvgMinutesSpent, na.rm = TRUE),
TotalAvgPercentage = mean(AvgPercentage, na.rm = TRUE),
TotalAvgHoursSpent = sum(AvgHoursSpent, na.rm = TRUE)
), by = ActivityLevel]
# Ensure the total average percentage for each activity level
summary_table <- summary_table[, .(
ActivityLevel,
TotalAvgMinutesSpent,
TotalAvgPercentage,
TotalAvgHoursSpent
)]
# Define custom colors for the Activity Levels
activity_colors <- c(
"Sedentary" = "#fff5f5",
"LightlyActive" = "#ffd9d9",
"FairlyActive" = "#FF8967",
"VeryActive" = "#FF6666"
)
# Create labels for the legend
summary_table[, legend_label := paste0(ActivityLevel, " (", round(TotalAvgPercentage, 2), "%)")]
# Create the pie chart using ggplot2