Background for this activity

I recently completed Google Data Analytics Professional Certificate Course. Here on this page I am performing the Process and Analysis phase of the case study. Case Study: This is for the Case Study of Bellabeat, a high-tech company that manufactures health-focused smart products that track data on activity, sleep, stress, and reproductive health to empower women with knowledge about their health and habits.

The Scenario

In my role as a junior analyst working in the marketing analyst team at Bellabeat, I am performing an analysis of smart device fitness data for the products provided by Bellabeat to gain insights on customer usage.

Step 3: Process Phase

Install the packages:

install.packages("tidyverse")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("skimr")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("janitor")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("lubridate")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("readr")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("reshape2")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
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(skimr)
library(janitor)
## 
## Attaching package: 'janitor'
## The following objects are masked from 'package:stats':
## 
##     chisq.test, fisher.test
library(lubridate)
library(readr)
library("reshape2")
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths

Importing the data sets:

Daily_Activity <- read_csv("dailyActivity_merged.csv")
## Rows: 940 Columns: 15
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): ActivityDate
## dbl (14): Id, TotalSteps, TotalDistance, TrackerDistance, LoggedActivitiesDi...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Daily_Calories <- read_csv("dailyCalories_merged.csv")
## Rows: 940 Columns: 3
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): ActivityDay
## dbl (2): Id, Calories
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Sleep_Day <- read_csv("sleepDay_merged.csv")
## Rows: 413 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): SleepDay
## dbl (4): Id, TotalSleepRecords, TotalMinutesAsleep, TotalTimeInBed
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Daily_Steps <- read_csv("dailySteps_merged.csv")
## Rows: 940 Columns: 3
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): ActivityDay
## dbl (2): Id, StepTotal
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Hourly_Intensities <- read_csv("hourlyIntensities_merged.csv")
## Rows: 22099 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): ActivityHour
## dbl (3): Id, TotalIntensity, AverageIntensity
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Previewing the datasets:

head(Daily_Activity)
## # A tibble: 6 × 15
##           Id ActivityDate TotalSteps TotalDistance TrackerDistance
##        <dbl> <chr>             <dbl>         <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
## # ℹ 10 more variables: LoggedActivitiesDistance <dbl>,
## #   VeryActiveDistance <dbl>, ModeratelyActiveDistance <dbl>,
## #   LightActiveDistance <dbl>, SedentaryActiveDistance <dbl>,
## #   VeryActiveMinutes <dbl>, FairlyActiveMinutes <dbl>,
## #   LightlyActiveMinutes <dbl>, SedentaryMinutes <dbl>, Calories <dbl>
head(Daily_Calories)
## # A tibble: 6 × 3
##           Id ActivityDay Calories
##        <dbl> <chr>          <dbl>
## 1 1503960366 4/12/2016       1985
## 2 1503960366 4/13/2016       1797
## 3 1503960366 4/14/2016       1776
## 4 1503960366 4/15/2016       1745
## 5 1503960366 4/16/2016       1863
## 6 1503960366 4/17/2016       1728
head(Daily_Steps)
## # A tibble: 6 × 3
##           Id ActivityDay StepTotal
##        <dbl> <chr>           <dbl>
## 1 1503960366 4/12/2016       13162
## 2 1503960366 4/13/2016       10735
## 3 1503960366 4/14/2016       10460
## 4 1503960366 4/15/2016        9762
## 5 1503960366 4/16/2016       12669
## 6 1503960366 4/17/2016        9705
head(Sleep_Day)
## # A tibble: 6 × 5
##           Id SleepDay        TotalSleepRecords TotalMinutesAsleep TotalTimeInBed
##        <dbl> <chr>                       <dbl>              <dbl>          <dbl>
## 1 1503960366 4/12/2016 12:0…                 1                327            346
## 2 1503960366 4/13/2016 12:0…                 2                384            407
## 3 1503960366 4/15/2016 12:0…                 1                412            442
## 4 1503960366 4/16/2016 12:0…                 2                340            367
## 5 1503960366 4/17/2016 12:0…                 1                700            712
## 6 1503960366 4/19/2016 12:0…                 1                304            320
head(Hourly_Intensities)
## # A tibble: 6 × 4
##           Id ActivityHour          TotalIntensity AverageIntensity
##        <dbl> <chr>                          <dbl>            <dbl>
## 1 1503960366 4/12/2016 12:00:00 AM             20            0.333
## 2 1503960366 4/12/2016 1:00:00 AM               8            0.133
## 3 1503960366 4/12/2016 2:00:00 AM               7            0.117
## 4 1503960366 4/12/2016 3:00:00 AM               0            0    
## 5 1503960366 4/12/2016 4:00:00 AM               0            0    
## 6 1503960366 4/12/2016 5:00:00 AM               0            0

I will be using the following datasets: Daily_Activity, Sleep_Day, Hourly_Intensities

Check for duplicate entries:

sum(duplicated(Daily_Activity))
## [1] 0
sum(duplicated(Sleep_Day))
## [1] 3
sum(duplicated(Hourly_Intensities))
## [1] 0

The Sleep_Day dataset has 3 duplicates.

Removing duplicates from the dataset:

And removing N/A or blank fields:

Sleep_Day <- Sleep_Day %>%
  distinct() %>%
  drop_na()

Verifying if the result is now correct:

sum(duplicated(Sleep_Day))
## [1] 0

Formatting

To make sure all the column names in each file are in the same format and have a correct syntax, let’s make all the column names format to lowercase:

Daily_Activity <- rename_with(Daily_Activity, tolower)

Sleep_Day <- rename_with(Sleep_Day, tolower)

Renaming

From the tibbles displayed, I found out that the date column has a different name in the files. To keep it consistent, let’s rename it as date:

Daily_Activity <- Daily_Activity %>% 
  rename(date = activitydate) %>% 
  mutate(date = as_date(date, format = "%m/%d/%Y"))

Sleep_Day <- Sleep_Day %>% 
  rename(date = sleepday) %>% 
   mutate(date = as_date(date, format = "%m/%d/%Y  %I:%M:%S %p"))

Merging datasets:

DailyActivity_Sleep <- merge(Daily_Activity, Sleep_Day, by=c("id", "date"))

glimpse(DailyActivity_Sleep)
## Rows: 410
## Columns: 18
## $ id                       <dbl> 1503960366, 1503960366, 1503960366, 150396036…
## $ date                     <date> 2016-04-12, 2016-04-13, 2016-04-15, 2016-04-…
## $ totalsteps               <dbl> 13162, 10735, 9762, 12669, 9705, 15506, 10544…
## $ totaldistance            <dbl> 8.50, 6.97, 6.28, 8.16, 6.48, 9.88, 6.68, 6.3…
## $ trackerdistance          <dbl> 8.50, 6.97, 6.28, 8.16, 6.48, 9.88, 6.68, 6.3…
## $ loggedactivitiesdistance <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ veryactivedistance       <dbl> 1.88, 1.57, 2.14, 2.71, 3.19, 3.53, 1.96, 1.3…
## $ moderatelyactivedistance <dbl> 0.55, 0.69, 1.26, 0.41, 0.78, 1.32, 0.48, 0.3…
## $ lightactivedistance      <dbl> 6.06, 4.71, 2.83, 5.04, 2.51, 5.03, 4.24, 4.6…
## $ sedentaryactivedistance  <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ veryactiveminutes        <dbl> 25, 21, 29, 36, 38, 50, 28, 19, 41, 39, 73, 3…
## $ fairlyactiveminutes      <dbl> 13, 19, 34, 10, 20, 31, 12, 8, 21, 5, 14, 23,…
## $ lightlyactiveminutes     <dbl> 328, 217, 209, 221, 164, 264, 205, 211, 262, …
## $ sedentaryminutes         <dbl> 728, 776, 726, 773, 539, 775, 818, 838, 732, …
## $ calories                 <dbl> 1985, 1797, 1745, 1863, 1728, 2035, 1786, 177…
## $ totalsleeprecords        <dbl> 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
## $ totalminutesasleep       <dbl> 327, 384, 412, 340, 700, 304, 360, 325, 361, …
## $ totaltimeinbed           <dbl> 346, 407, 442, 367, 712, 320, 377, 364, 384, …

Step 4: Analysis Phase

I will begin with calculating the average steps, average distance, average calories, and average of sleep minutes.

Averages <- DailyActivity_Sleep %>% 
  group_by(id) %>% 
  summarise(date,mean_daily_steps = mean(totalsteps), mean_distance = mean(totaldistance), mean_daily_calories = mean(calories), mean_daily_sleep = mean(totalminutesasleep))
## Warning: Returning more (or less) than 1 row per `summarise()` group was deprecated in
## dplyr 1.1.0.
## ℹ Please use `reframe()` instead.
## ℹ When switching from `summarise()` to `reframe()`, remember that `reframe()`
##   always returns an ungrouped data frame and adjust accordingly.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `summarise()` has grouped output by 'id'. You can override using the `.groups`
## argument.
head(Averages)
## # A tibble: 6 × 6
## # Groups:   id [1]
##           id date       mean_daily_steps mean_distance mean_daily_calories
##        <dbl> <date>                <dbl>         <dbl>               <dbl>
## 1 1503960366 2016-04-12           12406.          7.97               1872.
## 2 1503960366 2016-04-13           12406.          7.97               1872.
## 3 1503960366 2016-04-15           12406.          7.97               1872.
## 4 1503960366 2016-04-16           12406.          7.97               1872.
## 5 1503960366 2016-04-17           12406.          7.97               1872.
## 6 1503960366 2016-04-19           12406.          7.97               1872.
## # ℹ 1 more variable: mean_daily_sleep <dbl>
Min_Steps <- min(Averages$mean_daily_steps, na.rm = TRUE)
Min_Steps
## [1] 1490
Max_Steps <- max(Averages$mean_daily_steps, na.rm = TRUE)
Max_Steps
## [1] 19078.67

Now to classify the users based on their average daily steps:

User_Type <- Averages %>% 
  mutate(User_Type = case_when(
    mean_daily_steps < 4000 ~ "sedentary",
    mean_daily_steps >= 4000 & mean_daily_steps < 8000 ~ "lightly active",
    mean_daily_steps >= 8000 & mean_daily_steps <12000 ~ "fairly active",
    mean_daily_steps > 12000 ~ "very active"))

head(User_Type)
## # A tibble: 6 × 7
## # Groups:   id [1]
##           id date       mean_daily_steps mean_distance mean_daily_calories
##        <dbl> <date>                <dbl>         <dbl>               <dbl>
## 1 1503960366 2016-04-12           12406.          7.97               1872.
## 2 1503960366 2016-04-13           12406.          7.97               1872.
## 3 1503960366 2016-04-15           12406.          7.97               1872.
## 4 1503960366 2016-04-16           12406.          7.97               1872.
## 5 1503960366 2016-04-17           12406.          7.97               1872.
## 6 1503960366 2016-04-19           12406.          7.97               1872.
## # ℹ 2 more variables: mean_daily_sleep <dbl>, User_Type <chr>

Creating a data frame to use this in a visualization:

User_Type_Percent <- User_Type %>%
  group_by(User_Type) %>%
  summarise(total = n()) %>%
  mutate(totals = sum(total)) %>%
  group_by(User_Type) %>%
  summarise(total_percent = total / totals) %>%
  mutate(labels = scales::percent(total_percent))

User_Type_Percent$User_Type <- factor(User_Type_Percent$User_Type , levels = c("very active", "fairly active", "lightly active", "sedentary"))

head(User_Type_Percent)
## # A tibble: 4 × 3
##   User_Type      total_percent labels
##   <fct>                  <dbl> <chr> 
## 1 fairly active         0.632  63.17%
## 2 lightly active        0.237  23.66%
## 3 sedentary             0.0634 6.34% 
## 4 very active           0.0683 6.83%

Visualizing the categories created in a Bar Chart format to make the data easy to understand:

User_Type_Percent %>%
  ggplot(aes(x = User_Type, y = total_percent, fill = User_Type)) +
  geom_bar(stat = "identity", width = 0.7) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title = element_text(hjust = 0.5, size = 16, face = "bold", color = "darkgreen")
  ) +
  scale_fill_manual(values = c("#FF9999", "#66B2FF", "#99FF99", "#FFD700")) +
  geom_text(aes(label = labels), position = position_stack(vjust = 0.5)) +
  labs(
    title = "Distribution of User Types",
    x = "User Type",
    y = "Total Percent"
  )

We can also view it as a heatmap for different categories and users for different dates:

heatmap_data <- User_Type[, c("date", "id", "User_Type")]

# Melt the data for ggplot
melted_data <- reshape2::melt(heatmap_data, id.vars = c("date", "id"))

melted_data$date <- as.Date(melted_data$date)

# Create a ggplot heatmap with four discrete values
ggplot(melted_data, aes(x = date, y = factor(id), fill = value)) +
  geom_tile() +
  scale_fill_manual(values = c("#FFD700", "#FFA500", "#FF8C00", "#C71585")) +  
  labs(
    title = "Heatmap of Activity Category Over Different Dates",
    x = "Date",
    y = "ID",
    fill = "Activity Category"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_x_date(date_breaks = "1 day", date_labels = "%d %b")

We see more users to be “fairly active”.

Analysis of Sleep data:

ggplot(data = Sleep_Day, aes(x = totaltimeinbed, y = totalminutesasleep)) +
  geom_smooth(color = "#3366cc", fill = "#66a3ff", method = "auto", se = FALSE) +
  geom_jitter(color = "#ff9900", alpha = 0.7) +
  labs(
    title = "Total Time When Asleep Vs Time In Bed",
    x = "Total Time In Bed (minutes)",
    y = "Total Minutes Asleep"
  ) +
  theme_light()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Notably, the graphical representation suggested a linear correlation between these variables.

Analysis of Steps data:

Average_Steps <- DailyActivity_Sleep %>%
  group_by(id, date) %>%
  summarize(average_steps = mean(totalsteps))
## `summarise()` has grouped output by 'id'. You can override using the `.groups`
## argument.
# Result
print(Average_Steps)
## # A tibble: 410 × 3
## # Groups:   id [24]
##            id date       average_steps
##         <dbl> <date>             <dbl>
##  1 1503960366 2016-04-12         13162
##  2 1503960366 2016-04-13         10735
##  3 1503960366 2016-04-15          9762
##  4 1503960366 2016-04-16         12669
##  5 1503960366 2016-04-17          9705
##  6 1503960366 2016-04-19         15506
##  7 1503960366 2016-04-20         10544
##  8 1503960366 2016-04-21          9819
##  9 1503960366 2016-04-23         14371
## 10 1503960366 2016-04-24         10039
## # ℹ 400 more rows

Analysis of Steps taken in a week:

# Convert date to day of the week
DailyActivity_Sleep$day_of_week <- weekdays(DailyActivity_Sleep$date)

# Order days of the week
DailyActivity_Sleep$day_of_week <- factor(DailyActivity_Sleep$day_of_week, levels = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))

# Create a bar plot
ggplot(DailyActivity_Sleep, aes(x = day_of_week, y = totalsteps, fill = day_of_week)) +
   geom_col(fill =  '#800080') +
  labs(title = "Steps Taken Across Days of the Week", x = "Day of the Week", y = "Total Steps") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

From the Bar graph, users are most active on Tuesdays. And least steps are taken on Sunday.

Analysis of Hourly Intensity data:

Hourly_Intensities$ActivityHour <- as.POSIXct(Hourly_Intensities$ActivityHour, format="%m/%d/%Y %I:%M:%S %p")

# To extract the hour from the ActivityHour
Hourly_Intensities$Hour <- hour(Hourly_Intensities$ActivityHour)

# Now group by hour and calculate the total intensity for each hour
active_hours <- Hourly_Intensities %>%
  group_by(Hour) %>%
  summarize(TotalIntensity = sum(TotalIntensity))

# Let's find the hour with the maximum total intensity
max_intensity_hour <- active_hours %>%
  filter(TotalIntensity == max(TotalIntensity))

# Result
print(max_intensity_hour)
## # A tibble: 1 × 2
##    Hour TotalIntensity
##   <int>          <dbl>
## 1    18          19861

And we can visualize it like:

# Create a bar plot
ggplot(active_hours, aes(x = factor(Hour), y = TotalIntensity)) +
  geom_bar(stat = "identity", fill = "#90EE90", color = "black") +
  labs(
    title = "Active Hours of the Day based on Total Intensity",
    x = "Hour",
    y = "Total Intensity"
  ) +
  theme_minimal()

We can clearly see that the intensity of the activity is max from 17th hour to the 19th. 18th being at the peak.

Recommendations:

*To mitigate sedentary behavior, users could receive periodic notifications encouraging them to incorporate movement throughout their day.

*The average step count should ideally be in the recommended range of 8000–10000 steps given by the CDC. The app has an opportunity to inspire users to reach a healthier goal of 10000 steps daily for when their step count is less than 8000 on the given day.

*Observing a correlation between extended time in bed and increased sleep duration, the app could offer daily bedtime notifications. This not only contributes to enhancing sleep cycles but also promotes better mental and physical well-being.

*The insights imply a potential strategy to have notification feature prompting users to go to bed on certain points when the body is in resting condition(we can also make sure it is sent at nighttime). Such a feature could contribute to enhancing overall sleep duration and quality of sleep based on the observed relationship in the data analysis.

*On average, a user is most active on Tuesdays. and least active on Sundays. Bellabeat can notify the user to go for a walk on days like Sunday, Monday and Friday where the activity is the lowest.

*Encouraging users to engage in high-intensity exercise during the 5 to 8 PM period can be effective, given that the data indicates heightened activity levels during this period of the day.