1.ASK


1.1 About the business

Bellabeat is the go-to wellness brand for women with an ecosystem of products and services focused on women’s health.

Bellabeat’s mission is to empower women to reconnect with themselves, unleash their inner strengths and be what they were meant to be by developing wearables and accompanying products that monitor biometric and lifestyle data to help women better understand how their bodies work and make healthier choices.

Bellabeat focuses on giving women the tools to live in harmony with themselves.

1.2 Key stakeholders

• Urška Sršen: Bellabeat’s co-founder and Chief Creative Officer.

• Sando Mur: Mathematician and Bellabeat’s co-founder; key member of the Bellabeat executive team.

• Bellabeat marketing analytics team: A team of data analysts responsible for collecting, analyzing, and reporting data that helps guide Bellabeat’s marketing strategy.

1.3 Business task

Analyze FitBit fitness tracker data to gain insights into how consumers are using the FitBit app and discover trends for Bellabeat marketing strategy.

• What are some trends in smart device usage?

• How could these trends apply to Bellabeat customers?

• How could these trends help influence Bellabeat marketing strategy?


2.PREPARE


2.1 Data sources

FitBit Fitness Tracker Data is used for this project.

This dataset generated by respondents to a distributed survey via Amazon Mechanical Turk between 03.12.2016-05.12.2016.

Thirty eligible Fitbit users consented to the submission of personal tracker data, including minute-level output for physical activity, heart rate, and sleep monitoring.

This dataset contains 18 CSV files.

2.2 Import data

Three CSV files are selected and used for this project.

# Import CSV files into R
daily_activity <- read.csv("dailyActivity_merged.csv")
daily_sleep <- read.csv("sleepDay_merged.csv")
hourly_steps <- read.csv("hourlySteps_merged.csv")

2.3 Install and load packages

First install packages.

install.packages("tidyverse")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("plotly")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("knitr")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)

Then load packages.

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(knitr)
library(lubridate)
library(ggplot2)
library(dplyr)
library(forcats)

3.PROCESS


3.1 Clean data

Take a closer look at the data.

tibble(daily_activity)
## # A tibble: 940 × 15
##            Id ActivityDate TotalSteps TotalDistance TrackerDistance
##         <dbl> <chr>             <int>         <dbl>           <dbl>
##  1 1503960366 4/12/2016         13162          8.5             8.5 
##  2 1503960366 4/13/2016         10735          6.97            6.97
##  3 1503960366 4/14/2016         10460          6.74            6.74
##  4 1503960366 4/15/2016          9762          6.28            6.28
##  5 1503960366 4/16/2016         12669          8.16            8.16
##  6 1503960366 4/17/2016          9705          6.48            6.48
##  7 1503960366 4/18/2016         13019          8.59            8.59
##  8 1503960366 4/19/2016         15506          9.88            9.88
##  9 1503960366 4/20/2016         10544          6.68            6.68
## 10 1503960366 4/21/2016          9819          6.34            6.34
## # ℹ 930 more rows
## # ℹ 10 more variables: LoggedActivitiesDistance <dbl>,
## #   VeryActiveDistance <dbl>, ModeratelyActiveDistance <dbl>,
## #   LightActiveDistance <dbl>, SedentaryActiveDistance <dbl>,
## #   VeryActiveMinutes <int>, FairlyActiveMinutes <int>,
## #   LightlyActiveMinutes <int>, SedentaryMinutes <int>, Calories <int>
tibble(daily_sleep)
## # A tibble: 413 × 5
##            Id SleepDay       TotalSleepRecords TotalMinutesAsleep TotalTimeInBed
##         <dbl> <chr>                      <int>              <int>          <int>
##  1 1503960366 4/12/2016 12:…                 1                327            346
##  2 1503960366 4/13/2016 12:…                 2                384            407
##  3 1503960366 4/15/2016 12:…                 1                412            442
##  4 1503960366 4/16/2016 12:…                 2                340            367
##  5 1503960366 4/17/2016 12:…                 1                700            712
##  6 1503960366 4/19/2016 12:…                 1                304            320
##  7 1503960366 4/20/2016 12:…                 1                360            377
##  8 1503960366 4/21/2016 12:…                 1                325            364
##  9 1503960366 4/23/2016 12:…                 1                361            384
## 10 1503960366 4/24/2016 12:…                 1                430            449
## # ℹ 403 more rows

3.1.1 Naming conventions

All variables’ names are converted to lowercase and snake case where spaces between words are replaced with underscores.

daily_activity_c <- 
  daily_activity %>% 
  rename(id = Id,
         activity_date = ActivityDate, 
       total_steps = TotalSteps, 
       total_distance = TotalDistance,
       tracker_distance = TrackerDistance,
       logged_activities_distance = LoggedActivitiesDistance,
       very_active_distance = VeryActiveDistance, 
       moderately_active_distance = ModeratelyActiveDistance, 
       light_active_distance = LightActiveDistance, 
       sedentary_distance = SedentaryActiveDistance, 
       very_active_minutes = VeryActiveMinutes, 
       fairly_active_minutes = FairlyActiveMinutes, 
       lightly_active_minutes = LightlyActiveMinutes, 
       sedentary_minutes = SedentaryMinutes,
       calories = Calories)
daily_sleep_c <- 
  daily_sleep %>% 
  rename(id = Id,
         sleep_date = SleepDay, 
         total_sleep = TotalSleepRecords,
         total_minutes_asleep = TotalMinutesAsleep,
         total_minutes_in_bed = TotalTimeInBed)
hourly_steps <- 
  hourly_steps %>% 
  rename(id = Id,
         activity_hour = ActivityHour,
         step_total = StepTotal)

3.1.2 Missing value

First check if there is any missing value in the daily activity dataframe.

sum(is.na(daily_activity_c$total_steps))
## [1] 0

There isn’t any NA, however when I look at the CVS file there is a lot of “0”s. When there is “0”, it means the user did not use the device that day. I replace 0 with NA.

daily_activity_c$total_steps[daily_activity_c$total_steps == 0] <- NA
sum(is.na(daily_activity_c$total_steps))
## [1] 77

Now let’s get rid of the NAs.

daily_activity_c <- daily_activity_c %>%
  drop_na()

Same procedure applied to the daily sleep dataframe.

sum(is.na(daily_sleep_c$total_sleep))
## [1] 0

When I check there is no “0” in the table, but just to be safe I replace “0” with NA.

daily_sleep_c$total_sleep[daily_sleep_c$total_sleep == 0] <- NA

Then check again.

sum(is.na(daily_sleep_c$total_sleep))
## [1] 0

3.1.3 Remove duplicates

sum(duplicated(daily_activity_c))
## [1] 0
sum(duplicated(daily_sleep_c))
## [1] 3
sum(duplicated(hourly_steps))
## [1] 0
# Remove duplicated rows in daily sleep.
daily_sleep_c <- daily_sleep_c[!duplicated(daily_sleep_c), ] 

3.1.4 Fixing formatting issues

Change sleep date and activity date from character to date variable.

daily_sleep_c$sleep_date <- strptime(daily_sleep_c$sleep_date, "%m/%d/%Y %H:%M:%S")

daily_sleep_c$sleep_date <- as.Date(daily_sleep_c$sleep_date)
daily_activity_c$activity_date <- strptime(daily_activity_c$activity_date, "%m/%d/%Y")

daily_activity_c$activity_date <- as.Date(daily_activity_c$activity_date)

Change activity hour from character to datetime variable.

hourly_steps$date_and_time <- mdy_hms(hourly_steps$activity_hour)

4.ANALYZE


4.1 Steps vs calories

Change activity hour from character to datetime variable.

daily_activity_c %>% 
  ggplot(aes(total_steps, calories)) +
  geom_jitter(size = 2, color = "#ff7f50") +
  geom_smooth(method = lm, se = F, color = "#808080") +
  labs(x = "Steps",
       y = "Calories",
       title = "") +
  theme(axis.line = element_line(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        axis.title.x = element_text(size = 16, color = "#808080"),
        axis.title.y = element_text(size = 16, color = "#808080"))
## `geom_smooth()` using formula = 'y ~ x'

Correlation Test

cor.test(daily_activity_c$total_steps, daily_activity_c$calories)
## 
##  Pearson's product-moment correlation
## 
## data:  daily_activity_c$total_steps and daily_activity_c$calories
## t = 19.936, df = 861, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.5145440 0.6059895
## sample estimates:
##       cor 
## 0.5619815

Linear regression

daily_activity_c %>% 
lm(calories ~ total_steps, data = .) %>% 
  summary()
## 
## Call:
## lm(formula = calories ~ total_steps, data = .)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1976.66  -385.52   -43.53   457.04  1865.15 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 1.669e+03  3.998e+01   41.75   <2e-16 ***
## total_steps 8.323e-02  4.175e-03   19.94   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 581.6 on 861 degrees of freedom
## Multiple R-squared:  0.3158, Adjusted R-squared:  0.315 
## F-statistic: 397.4 on 1 and 861 DF,  p-value: < 2.2e-16

There is a positive correlation between steps taken and calories burned which means when someone is more active, they will burn more calories.

4.2 Steps vs sleep time

Rename the columns in daily sleep and daily activity and merge the two dataframes.

daily_sleep_c <-
  daily_sleep_c %>% 
  rename(date = sleep_date)
daily_activity_c <-
  daily_activity_c %>% 
  rename(date = activity_date)
daily_sleep_activity <- inner_join(daily_sleep_c, daily_activity_c, by = c("id", "date")) 
n_distinct(daily_sleep_activity$id)
## [1] 24
daily_sleep_activity %>% 
  ggplot(aes(total_steps, total_minutes_asleep)) +
  geom_point(size = 2, color = "#ff7f50") +
    labs(x = "Steps",
       y = "Amount of Sleep (Minutes Asleep)",
       title = "") +
  theme(axis.line = element_line(),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      axis.title.x = element_text(size = 16, color = "#808080"),
      axis.title.y = element_text(size = 16, color = "#808080"))

Correlation test

cor.test(daily_sleep_activity$total_steps, daily_sleep_activity$total_minutes_asleep)
## 
##  Pearson's product-moment correlation
## 
## data:  daily_sleep_activity$total_steps and daily_sleep_activity$total_minutes_asleep
## t = -3.9164, df = 408, p-value = 0.0001054
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.28199288 -0.09525253
## sample estimates:
##        cor 
## -0.1903439

Linear regression

daily_sleep_activity %>% 
  lm(total_minutes_asleep ~ total_steps, data = .) %>% 
  summary()
## 
## Call:
## lm(formula = total_minutes_asleep ~ total_steps, data = .)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -386.32  -56.67   13.31   70.32  350.99 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 465.423623  13.138907  35.423  < 2e-16 ***
## total_steps  -0.005432   0.001387  -3.916 0.000105 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 116.6 on 408 degrees of freedom
## Multiple R-squared:  0.03623,    Adjusted R-squared:  0.03387 
## F-statistic: 15.34 on 1 and 408 DF,  p-value: 0.0001054

It shows that there is a weak negative correlation between the amount of sleep and steps which seems counter-intuitive.

4.3 User type

Categorize users into three types by their daily usage: high use, moderate use, low use.

• high use - users who use their device between 21 and 31 days.

• moderate use - users who use their device between 11 and 20 days.

• low use - users who use their device between 1 and 10 days.

First change id from numeric to character variable then create a new variable as user name.

daily_sleep_activity$id <- as.character(daily_sleep_activity$id)
daily_sleep_activity<- daily_sleep_activity %>% 
  mutate(user_name = recode(id, 
                            '1503960366' = "user1", 
                            '1624580081' = "user2",
                            '1644430081' = "user3",
                            '1844505072' = "user4",
                            '1927972279' = "user5",
                            '2022484408' = "user6",
                            '2026352035' = "user7",
                            '2320127002' = "user8",
                            '2347167796' = "user9",
                            '2873212765' = "user10",
                            '3372868164' = "user11",
                            '3977333714' = "user12",
                            '4020332650' = "user13",
                            '4057192912' = "user14",
                            '4319703577' = "user15",
                            '4388161847' = "user16",
                            '4445114986' = "user17",
                            '4558609924' = "user18",
                            '4702921684' = "user19",
                            '5553957443' = "user20",
                            '5577150313' = "user21",
                            '6117666160' = "user22",
                            '6290855005' = "user23",
                            '6775888955' = "user24",
                            '6962181067' = "user25",
                            '7007744171' = "user26",
                            '7086361926' = "user27",
                            '8053475328' = "user28",
                            '8253242879' = "user29",
                            '8378563200' = "user30",
                            '8583815059' = "user31",
                            '8792009665' = "user32",
                            '8877689391' = "user33"))
n_distinct(daily_sleep_activity$user_name)
## [1] 24
daily_use <- daily_sleep_activity %>%
  group_by(user_name) %>%
  summarize(days_used=n())

Create an interactive graph with plotly.

daily_use %>%
  plot_ly(x = ~days_used,
          y = ~user_name,
          type = "scatter",
          mode = "markers",
          text = ~paste("User name:", user_name, "<br>Days used:", days_used),
          marker = list(size = ~days_used,
                        color = "steelblue",
                        line = list(color = "steelblue", width = 2)),
          showlegend = FALSE) %>%
  add_markers(hoverinfo = "text",
              opacity = I(0.6)) %>%
  layout(title = "Days of Usage",
                 yaxis = list(zeroline = FALSE,
                              showgrid = FALSE,
                              title = ""),
                 xaxis = list(zeroline = FALSE,
                              showgrid = FALSE, 
                              title = ""))
user_type <- daily_use %>%
  mutate(usage = case_when(
    days_used >= 1 & days_used <= 10 ~ "low use",
    days_used >= 11 & days_used <= 20 ~ "moderate use", 
    days_used >= 21 & days_used <= 31 ~ "high use", 
  ))
user_type_freq <- user_type %>%
  group_by(usage) %>%
  summarise(frequency = n())

Create a bar chart.

user_type_freq %>% 
  ggplot(aes(usage, frequency)) +
  geom_bar(stat = "identity", linewidth = 4, alpha = 0.7, fill = "steelblue") +
  geom_label(aes(label = frequency), fill = "white", color = "#808080", size = 8, vjust = 0.5)+
  theme_minimal() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_text(size = 6),
        axis.title.x = element_text(size = 16, color = "#808080")) +
  labs(x = "usage type",
       y = "",
       title = "")

user_type_percent<- user_type %>%
  group_by(usage) %>%
  summarize(total = n()) %>%
  mutate(totals = sum(total)) %>%
  group_by(usage) %>%
  summarize(total_percent = total / totals) %>%
  mutate(percent_label = scales::percent(total_percent)) %>%
  mutate(usage = fct_infreq(usage)) %>%
  mutate(usage = fct_rev(usage))

Let’s show the result in a pie chart.

user_type_percent %>%
  ggplot(aes(x = "", y = total_percent, fill = usage, label = percent_label)) +
  geom_col(color = "white") +
  geom_text(color = "black", position = position_stack(vjust = 0.5)) +
  coord_polar("y", start = 0) +
  ggtitle("User Type") +
  theme_void() +
  theme(plot.title = element_text(hjust = 0.5, size = 20),
        axis.title.y = element_blank(),
        axis.title.x = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        panel.grid = element_blank()) +
  guides(fill = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values = c("#a1c6e6", "#6ba4d5", "steelblue"), name = "Usage") + 
  theme(legend.text = element_text(size = 10),
                                                               legend.title = element_text(hjust = 0.5, size = 12))

4.4 Active days of the week

Let’s explore a little bit more on what days users are more active. Weekends or weekdays?

   weekday_sleep_activity <- daily_sleep_activity %>%
                     mutate(weekday = weekdays(date))
weekday_sleep_activity$weekday <-ordered(weekday_sleep_activity$weekday, levels=c("Monday", "Tuesday", "Wednesday", "Thursday",
                                                                            "Friday", "Saturday", "Sunday"))

Create an interactive boxplot using plotly.

weekday_sleep_activity %>% 
  plot_ly(y = ~weekday,
          x = ~total_steps,
          type = "box",
          color = ~weekday,
          showlegend = FALSE,
          boxmean = TRUE) %>%
  layout(xaxis = list(title = "Steps",
                      showgrid = FALSE,
                      zeroline = FALSE),
         yaxis = list(title = ""))

Users are more active on Saturdays, Mondays, and Tuesdays.

Create an interactive heatmap for hourly steps.

hourly_steps$date <- as.Date(hourly_steps$date_and_time)
hourly_steps$time <- format(as.POSIXct(hourly_steps$date_and_time),
                            format = "%H:%M:%S")
heatmap_steps <- hourly_steps %>%
  ggplot(aes(x = time, y = date, fill = step_total)) +
  geom_tile() +
  scale_fill_gradient(low = "white", high = "red") +
  theme_minimal() +
  theme(axis.text.x= element_text(angle = 60)) +
  labs(title= "Hourly Steps During 31 Days",
       fill = "average\nsteps")
ggplotly(heatmap_steps) %>%
  layout(yaxis = list(zeroline = FALSE,
                    showgrid = FALSE,
                    title = ""), 
       xaxis = list(zeroline = FALSE,
                    showgrid = FALSE,
                    title = ""))
## Warning in matrix(g$fill_plotlyDomain, nrow = length(y), ncol = length(x), :
## data length [22107] is not a sub-multiple or multiple of the number of rows
## [31]
## Warning in matrix(g$hovertext, nrow = length(y), ncol = length(x), byrow =
## TRUE): data length [22107] is not a sub-multiple or multiple of the number of
## rows [31]

4.5 Daily sleep of the week

Create an interactive boxplot for daily sleep with means.

weekday_sleep_activity %>% 
  plot_ly(y = ~weekday,
          x = ~total_minutes_asleep,
          type = "box",
          color = ~weekday,
          showlegend = FALSE,
          boxmean = TRUE) %>%
  layout(xaxis = list(title = "Amount of Sleep (Minutes Asleep)",
                      showgrid = FALSE),
         yaxis = list(title = ""))

Users sleep more on Sundays and Wednesdays.


5.SHARE


5.1 Recommendations

1.Acquire Recent User Behavior Data: To gain better insights into user preferences, invest in acquiring recent user behavior data, including usage patterns, feedback, and demographic information, ideally on current BellaBeat users.

2.Explore Strategic Partnerships: Consider forging strategic partnerships with recognized brands like Apple or Lululemon to create a trendy and widely-recognized fitness device. The potential benefits are shared marketing efforts and expanded customer reach.

3.Introduce Targeted Discounts: Implement a tiered subscription discount system, offering incentives to both new and loyal users. For example, provide a 10% discount for new subscribers and a 20% discount for users who have maintained subscriptions for six months or more.

4.Loyalty Rewards Program: Launch a loyalty rewards program for users in the moderate or high usage groups. Define specific rewards, such as exclusive content, early access to new features, or discounts on future purchases, and establish clear criteria for qualification.

5.2 Session Info

sessionInfo()
## R version 4.3.2 (2023-10-31)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.6 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/atlas/libblas.so.3.10.3 
## LAPACK: /usr/lib/x86_64-linux-gnu/atlas/liblapack.so.3.10.3;  LAPACK version 3.9.0
## 
## locale:
##  [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
##  [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
##  [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
## [10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   
## 
## time zone: UTC
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] knitr_1.45      plotly_4.10.3   lubridate_1.9.3 forcats_1.0.0  
##  [5] stringr_1.5.0   dplyr_1.1.3     purrr_1.0.2     readr_2.1.4    
##  [9] tidyr_1.3.0     tibble_3.2.1    ggplot2_3.4.4   tidyverse_2.0.0
## 
## loaded via a namespace (and not attached):
##  [1] sass_0.4.7        utf8_1.2.3        generics_0.1.3    lattice_0.21-9   
##  [5] stringi_1.7.12    hms_1.1.3         digest_0.6.33     magrittr_2.0.3   
##  [9] evaluate_0.21     grid_4.3.2        timechange_0.2.0  fastmap_1.1.1    
## [13] Matrix_1.6-1.1    jsonlite_1.8.7    httr_1.4.7        mgcv_1.9-0       
## [17] fansi_1.0.4       crosstalk_1.2.0   viridisLite_0.4.2 scales_1.2.1     
## [21] lazyeval_0.2.2    jquerylib_0.1.4   cli_3.6.1         rlang_1.1.1      
## [25] ellipsis_0.3.2    munsell_0.5.0     splines_4.3.2     withr_2.5.0      
## [29] cachem_1.0.8      yaml_2.3.7        tools_4.3.2       tzdb_0.4.0       
## [33] colorspace_2.1-0  vctrs_0.6.3       R6_2.5.1          lifecycle_1.0.3  
## [37] htmlwidgets_1.6.2 pkgconfig_2.0.3   pillar_1.9.0      bslib_0.5.1      
## [41] gtable_0.3.4      glue_1.6.2        data.table_1.14.8 highr_0.10       
## [45] xfun_0.40         tidyselect_1.2.0  rstudioapi_0.15.0 farver_2.1.1     
## [49] nlme_3.1-163      htmltools_0.5.6   labeling_0.4.2    rmarkdown_2.24   
## [53] compiler_4.3.2