Setting up my environment

Note: load ‘tidyverse’ package that has most library we’ll be using thought our analysis

options(repos = c(CRAN = "https://cran.rstudio.com"))
install.packages("tidyverse")
## Installing package into 'C:/Users/LENOVO/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'tidyverse' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\LENOVO\AppData\Local\Temp\RtmpKeuyAL\downloaded_packages
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.2
## ── 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.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ 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

Load ‘readxl’ and upload clean excelfile ‘DailyActivity_xlx’

library(readxl)
DailyActivity_xlx <- read_excel("C:/Users/LENOVO/Desktop/Fitness Extract/Fitabase/DailyActivity.xlx.xlsx")
## New names:
## • `` -> `...3`

View data type

str(DailyActivity_xlx)
## tibble [940 × 16] (S3: tbl_df/tbl/data.frame)
##  $ Id                      : num [1:940] 1.5e+09 1.5e+09 1.5e+09 1.5e+09 1.5e+09 ...
##  $ ActivityDate            : POSIXct[1:940], format: "2016-04-12" "2016-04-13" ...
##  $ ...3                    : logi [1:940] NA NA NA NA NA NA ...
##  $ TotalSteps              : num [1:940] 13162 10735 10460 9762 12669 ...
##  $ TotalDistance           : num [1:940] 8.5 6.97 6.74 6.28 8.16 ...
##  $ TrackerDistance         : num [1:940] 8.5 6.97 6.74 6.28 8.16 ...
##  $ LoggedActivitiesDistance: num [1:940] 0 0 0 0 0 0 0 0 0 0 ...
##  $ VeryActiveDistance      : num [1:940] 1.88 1.57 2.44 2.14 2.71 ...
##  $ ModeratelyActiveDistance: num [1:940] 0.55 0.69 0.4 1.26 0.41 ...
##  $ LightActiveDistance     : num [1:940] 6.06 4.71 3.91 2.83 5.04 ...
##  $ SedentaryActiveDistance : num [1:940] 0 0 0 0 0 0 0 0 0 0 ...
##  $ VeryActiveMinutes       : num [1:940] 25 21 30 29 36 38 42 50 28 19 ...
##  $ FairlyActiveMinutes     : num [1:940] 13 19 11 34 10 20 16 31 12 8 ...
##  $ LightlyActiveMinutes    : num [1:940] 328 217 181 209 221 164 233 264 205 211 ...
##  $ SedentaryMinutes        : num [1:940] 728 776 1218 726 773 ...
##  $ Calories                : num [1:940] 1985 1797 1776 1745 1863 ...

Note: plot find distance covered which day are people most active

ggplot (data = DailyActivity_xlx) +
  geom_point(mapping = aes( x = ActivityDate , y = VeryActiveDistance)) +
  labs(title = "Distance covered when people are most active",
       subtitle = "From April 12th to May 11th")

Conclusion: Most people are cover less than 5Km In day

Import sleepDay_merged_xlx dataset

library(readxl)
sleepDay_merged_xlx <- read_excel("C:/Users/LENOVO/Desktop/Fitness Extract/Fitabase/sleepDay_merged.xlx.xlsx")

Merge the DailyActivity_xlx and sleepDay_merged_xlx

Dailyactivityandsleep  <- DailyActivity_xlx %>% inner_join( sleepDay_merged_xlx, 
                              by=c("Id" = "Id", 
                                   "ActivityDate" = "Sleepday"))

check data types

str(Dailyactivityandsleep)
## tibble [411 × 21] (S3: tbl_df/tbl/data.frame)
##  $ Id                      : num [1:411] 1.5e+09 1.5e+09 1.5e+09 1.5e+09 1.5e+09 ...
##  $ ActivityDate            : POSIXct[1:411], format: "2016-04-12" "2016-04-13" ...
##  $ ...3                    : logi [1:411] NA NA NA NA NA NA ...
##  $ TotalSteps              : num [1:411] 13162 10735 9762 12669 9705 ...
##  $ TotalDistance           : num [1:411] 8.5 6.97 6.28 8.16 6.48 ...
##  $ TrackerDistance         : num [1:411] 8.5 6.97 6.28 8.16 6.48 ...
##  $ LoggedActivitiesDistance: num [1:411] 0 0 0 0 0 0 0 0 0 0 ...
##  $ VeryActiveDistance      : num [1:411] 1.88 1.57 2.14 2.71 3.19 ...
##  $ ModeratelyActiveDistance: num [1:411] 0.55 0.69 1.26 0.41 0.78 ...
##  $ LightActiveDistance     : num [1:411] 6.06 4.71 2.83 5.04 2.51 ...
##  $ SedentaryActiveDistance : num [1:411] 0 0 0 0 0 0 0 0 0 0 ...
##  $ VeryActiveMinutes       : num [1:411] 25 21 29 36 38 50 28 19 41 39 ...
##  $ FairlyActiveMinutes     : num [1:411] 13 19 34 10 20 31 12 8 21 5 ...
##  $ LightlyActiveMinutes    : num [1:411] 328 217 209 221 164 264 205 211 262 238 ...
##  $ SedentaryMinutes        : num [1:411] 728 776 726 773 539 775 818 838 732 709 ...
##  $ Calories                : num [1:411] 1985 1797 1745 1863 1728 ...
##  $ TotalSleepRecords       : num [1:411] 1 2 1 2 1 1 1 1 1 1 ...
##  $ TotalMinutesAsleep      : num [1:411] 327 384 412 340 700 304 360 325 361 430 ...
##  $ TotalHrsAsleep          : num [1:411] 5.45 6.4 6.87 5.67 11.67 ...
##  $ TotalTimeInBed          : num [1:411] 346 407 442 367 712 320 377 364 384 449 ...
##  $ TotalHrsInBed           : num [1:411] 5.77 6.78 7.37 6.12 11.87 ...

plot graph to see relationship between steps and calories

ggplot (data = Dailyactivityandsleep) +
  geom_point(mapping = aes(x= TotalSteps , y=Calories )) +
  labs(title = "Step relation to Calories")

Conclusion there is a general increase in calories burn with an increase in steps

Visualize to see relationship between calories and sleep

ggplot (data = Dailyactivityandsleep) +
  geom_point(mapping = aes(x= TotalHrsAsleep , y=Calories )) +
  labs(title = "Step relation to Calories")

Conclusion there is no correlation between calories and sleep

upload weight data set

Load ‘readr’ and upload a csv file ‘weightLogInfo_merged’

library(readr)
weightLogInfo_merged <- read_csv("C:/Users/LENOVO/Desktop/Fitness Extract/Fitabase/weightLogInfo_merged.csv")
## Rows: 67 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Date
## dbl (6): Id, WeightKg, WeightPounds, Fat, BMI, LogId
## lgl (1): IsManualReport
## 
## ℹ 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.

Have an overview of dataset

str(weightLogInfo_merged)
## spc_tbl_ [67 × 8] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Id            : num [1:67] 1.50e+09 1.50e+09 1.93e+09 2.87e+09 2.87e+09 ...
##  $ Date          : chr [1:67] "5/2/2016 11:59:59 PM" "5/3/2016 11:59:59 PM" "4/13/2016 1:08:52 AM" "4/21/2016 11:59:59 PM" ...
##  $ WeightKg      : num [1:67] 52.6 52.6 133.5 56.7 57.3 ...
##  $ WeightPounds  : num [1:67] 116 116 294 125 126 ...
##  $ Fat           : num [1:67] 22 NA NA NA NA 25 NA NA NA NA ...
##  $ BMI           : num [1:67] 22.6 22.6 47.5 21.5 21.7 ...
##  $ IsManualReport: logi [1:67] TRUE TRUE FALSE TRUE TRUE TRUE ...
##  $ LogId         : num [1:67] 1.46e+12 1.46e+12 1.46e+12 1.46e+12 1.46e+12 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Id = col_double(),
##   ..   Date = col_character(),
##   ..   WeightKg = col_double(),
##   ..   WeightPounds = col_double(),
##   ..   Fat = col_double(),
##   ..   BMI = col_double(),
##   ..   IsManualReport = col_logical(),
##   ..   LogId = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>

Change date column to Date / POSIXct data type

1st Revome AM from string characters in Date column Then remove remove PM from string characters in Date column

weightLogInfo_merged$Date<-gsub("AM","",as.character(weightLogInfo_merged$Date))
weightLogInfo_merged$Date<-gsub("PM","",as.character(weightLogInfo_merged$Date))
View(weightLogInfo_merged)

Change date column to Date / POSIXct data type

weightLogInfo_merged$Date <- as.POSIXct(weightLogInfo_merged$Date, 
                                   format = "%m/%d/%Y %H:%M:%S") 

Separate date and time in 2 differnt columns

1st separate date and store date in ‘Date2’ Column Then separate time store time in ‘time’ column

weightLogInfo_merged$Date2 <- as.Date (weightLogInfo_merged$Date)
weightLogInfo_merged$time <- format(as.POSIXct(
  weightLogInfo_merged$Date),format = "%H:%M:%S")

Check date types to confirm if code was successfully executed

str(weightLogInfo_merged)
## spc_tbl_ [67 × 10] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Id            : num [1:67] 1.50e+09 1.50e+09 1.93e+09 2.87e+09 2.87e+09 ...
##  $ Date          : POSIXct[1:67], format: "2016-05-02 11:59:59" "2016-05-03 11:59:59" ...
##  $ WeightKg      : num [1:67] 52.6 52.6 133.5 56.7 57.3 ...
##  $ WeightPounds  : num [1:67] 116 116 294 125 126 ...
##  $ Fat           : num [1:67] 22 NA NA NA NA 25 NA NA NA NA ...
##  $ BMI           : num [1:67] 22.6 22.6 47.5 21.5 21.7 ...
##  $ IsManualReport: logi [1:67] TRUE TRUE FALSE TRUE TRUE TRUE ...
##  $ LogId         : num [1:67] 1.46e+12 1.46e+12 1.46e+12 1.46e+12 1.46e+12 ...
##  $ Date2         : Date[1:67], format: "2016-05-02" "2016-05-03" ...
##  $ time          : chr [1:67] "11:59:59" "11:59:59" "01:08:52" "11:59:59" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Id = col_double(),
##   ..   Date = col_character(),
##   ..   WeightKg = col_double(),
##   ..   WeightPounds = col_double(),
##   ..   Fat = col_double(),
##   ..   BMI = col_double(),
##   ..   IsManualReport = col_logical(),
##   ..   LogId = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>

Plot to find relationship between weight and BMI

ggplot (data = weightLogInfo_merged) +
  geom_line(mapping = aes(x= WeightKg , y=BMI )) +
  labs(title = "Weight and BMI relationship")

Conclusion individuals Body Mass Index increases with Weight Give personalized Recommendation to our clients, IE Best diet and physical exercise to achieve and Ideal BMI

Merge Dailyactivityandsleep and weightLogInfo_merged on id and date

Create a new data frame ‘Dailyactivity_sleepnWeight’ To tell the relationship between weight and calories

Dailyactivity_sleepnWeight  <- Dailyactivityandsleep %>% inner_join( weightLogInfo_merged, 
                                                            by=c("Id" = "Id", 
                                                                 "ActivityDate" = "Date2"))

Plot weight against Calories

ggplot (data = Dailyactivity_sleepnWeight) +
  geom_point(mapping = aes(x=WeightKg , y=Calories )) +
  labs(title = "Weight and Calories relationship")

Conclusion: There is no exact correlation between the 2 varianbles

Plot Weight against Total steps

ggplot (data = Dailyactivity_sleepnWeight) +
  geom_point(mapping = aes(x=WeightKg , y=TotalSteps )) +
  labs(title = "Weight and Steps relationship")

Conclusion: There is no exact correlation between the 2 varianbles

#Plot Calories and BMI Relationshiop

ggplot (data = Dailyactivity_sleepnWeight) +
  geom_point(mapping = aes(x=Calories , y=BMI ))+
  labs(title = "Calories and BMI relationship")

Conclusion: There is no exact correlation between the 2 varianbles

Upload heartrate data set

Load ‘readr’ and upload a csv file ‘heartrate_seconds_merged’

library(readr)
heartrate_seconds_merged <- read_csv("C:/Users/LENOVO/Desktop/Fitness Extract/Fitabase/heartrate_seconds_merged.csv")
## Rows: 2483658 Columns: 3
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Time
## dbl (2): Id, Value
## 
## ℹ 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.

Check data types in ‘heartrate_seconds_merged’

str(heartrate_seconds_merged)
## spc_tbl_ [2,483,658 × 3] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Id   : num [1:2483658] 2.02e+09 2.02e+09 2.02e+09 2.02e+09 2.02e+09 ...
##  $ Time : chr [1:2483658] "4/12/2016 7:21:00 AM" "4/12/2016 7:21:05 AM" "4/12/2016 7:21:10 AM" "4/12/2016 7:21:20 AM" ...
##  $ Value: num [1:2483658] 97 102 105 103 101 95 91 93 94 93 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Id = col_double(),
##   ..   Time = col_character(),
##   ..   Value = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>

Change Time column to Date / POSIXct data type

1st Remove AM from string characters in Time column Then remove remove PM from string characters in Time column

heartrate_seconds_merged$Time <-gsub("AM","",as.character(heartrate_seconds_merged$Time))
heartrate_seconds_merged$Time <-gsub("PM","",as.character(heartrate_seconds_merged$Time))

Change ‘date’ column to Date / POSIXct data type

heartrate_seconds_merged$Time <- as.POSIXct(heartrate_seconds_merged$Time, 
                                        format = "%m/%d/%Y %H:%M:%S")

Seperate columns by date and time

1st seperate ‘date’ from ‘time’ column store date in ‘date’ column

heartrate_seconds_merged$Date <- as.Date (heartrate_seconds_merged$Time)

Then seperate time from ‘time’ column save time in ‘time2’ column

heartrate_seconds_merged$time2 <- format(as.POSIXct(
  heartrate_seconds_merged$Time),format = "%H:%M:%S")

View heartrate_seconds_merged data frame

tibble(heartrate_seconds_merged)
## # A tibble: 2,483,658 × 5
##            Id Time                Value Date       time2   
##         <dbl> <dttm>              <dbl> <date>     <chr>   
##  1 2022484408 2016-04-12 07:21:00    97 2016-04-12 07:21:00
##  2 2022484408 2016-04-12 07:21:05   102 2016-04-12 07:21:05
##  3 2022484408 2016-04-12 07:21:10   105 2016-04-12 07:21:10
##  4 2022484408 2016-04-12 07:21:20   103 2016-04-12 07:21:20
##  5 2022484408 2016-04-12 07:21:25   101 2016-04-12 07:21:25
##  6 2022484408 2016-04-12 07:22:05    95 2016-04-12 07:22:05
##  7 2022484408 2016-04-12 07:22:10    91 2016-04-12 07:22:10
##  8 2022484408 2016-04-12 07:22:15    93 2016-04-12 07:22:15
##  9 2022484408 2016-04-12 07:22:20    94 2016-04-12 07:22:20
## 10 2022484408 2016-04-12 07:22:25    93 2016-04-12 07:22:25
## # ℹ 2,483,648 more rows

Group data by ID and Date store output in ‘DayHeartrate’ data frame

DailyHr_records <- heartrate_seconds_merged %>% group_by(Id,Date) %>% 
  summarise(Hraterecords_in_a_Day = sum(Value),
            .groups = 'drop')

Find average Heart rate

mean(heartrate_seconds_merged$Value)
## [1] 77.32842

Conclusion average heart rate in a minute is 77

User with the maximum heartrate in ‘heartrate_seconds_merged’

heartrate_seconds_merged[which.max(heartrate_seconds_merged$Value),]
## # A tibble: 1 × 5
##           Id Time                Value Date       time2   
##        <dbl> <dttm>              <dbl> <date>     <chr>   
## 1 2022484408 2016-04-21 04:31:40   203 2016-04-21 04:31:40

##check user activities on that day from that might have contributed to this in ‘DailyActivity_xlx’

df1 <- DailyActivity_xlx[DailyActivity_xlx$Id == 2022484408 ,]
View(df1)
DailyActivity_xlx[DailyActivity_xlx$Id == 2022484408 & DailyActivity_xlx$TotalSteps == 12453 ,]
## # A tibble: 1 × 16
##           Id ActivityDate        ...3  TotalSteps TotalDistance TrackerDistance
##        <dbl> <dttm>              <lgl>      <dbl>         <dbl>           <dbl>
## 1 2022484408 2016-04-21 00:00:00 NA         12453          8.74            8.74
## # ℹ 10 more variables: LoggedActivitiesDistance <dbl>,
## #   VeryActiveDistance <dbl>, ModeratelyActiveDistance <dbl>,
## #   LightActiveDistance <dbl>, SedentaryActiveDistance <dbl>,
## #   VeryActiveMinutes <dbl>, FairlyActiveMinutes <dbl>,
## #   LightlyActiveMinutes <dbl>, SedentaryMinutes <dbl>, Calories <dbl>

conclusion: on this day user “2022484408” covered a distance of 8.74 and had 12453 step, this is not sufficient enough evidence justify why user “2022484408” had such a high heart rate however from a closer look it’s the day he burnt most calories i.e “3158”

User with the minimum heartrate in ‘heartrate_seconds_merged’

heartrate_seconds_merged[which.min(heartrate_seconds_merged$Value),]
## # A tibble: 1 × 5
##           Id Time                Value Date       time2   
##        <dbl> <dttm>              <dbl> <date>     <chr>   
## 1 5577150313 2016-05-04 02:00:10    36 2016-05-03 02:00:10

Conclusion: from the tibble above it’s sufficient to say user “5577150313” might have been asleep since this data was recorded during night hours where human bodies processes slow down leading to a decrease in heart rate

Find the number approximate interval in seconds our device records heartrate data

Cont the number of records per user in a day in data.frame ‘Number_of_Hr_Records_InAday’

Number_of_Hr_Records_InAday <- heartrate_seconds_merged %>% group_by(Id,Date) %>% 
  summarise(total_count=n(),
            .groups = 'drop')

##Find the average counts per user our device records data in a day

mean(Number_of_Hr_Records_InAday$total_count)
## [1] 7015.983

Find the number approximate interval in seconds our device records heartrate data

86400/mean(Number_of_Hr_Records_InAday$total_count)
## [1] 12.31474

Conclusion: this is to say that bellabeat need to to improve it’s device to give data at least every second so that user can have the most accurate data real-time

Merge DayHeartrate and DailyActivity_xlx on Id and Date

heartrate_Dailyactivity <- DailyActivity_xlx %>% inner_join ( Number_of_Hr_Records_InAday,
                                                                     by=c("Id" = "Id", 
                                                                          "ActivityDate" = "Date"))

plot heartrate records against Calories to see how bellabeat devices record data

fix the scientific notations in Y axis

Load scales library

library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
ggplot (data = heartrate_Dailyactivity) +
  geom_point(mapping = aes(x=total_count , y=Calories )) +
  labs(title = "Calories and Heart rate records relatiion",
       subtitle = "See if our devices are biased") +
  scale_x_continuous(labels = comma_format(big.mark = ","))

check which Person has max heartrate records

DailyHr_records[which.max(DailyHr_records$Hraterecords_in_a_Day),]
## # A tibble: 1 × 3
##           Id Date       Hraterecords_in_a_Day
##        <dbl> <date>                     <dbl>
## 1 4020332650 2016-05-04               2879642

Check user “4020332650” data entry accuracy in heartrate_seconds_merged

user_4020332650 <-heartrate_seconds_merged[heartrate_seconds_merged$Id == "4020332650" ,]

Conclusion: user ‘4020332650’ get their heart rate data after 3 seconds thus the have the most accurate data among the rest of the users

check user “4020332650” weight & BMI in

## Create new data set ‘Id_BMI_Weight’

Id_BMI_Weight <-weightLogInfo_merged %>% select(Id ,WeightKg ,BMI)

Check user BMI and Weight

Id_BMI_Weight[Id_BMI_Weight$Id == "4020332650",] %>% 
  view()

Conclusion: No such user in the ‘weightLogInfo_merged’, this is to show that user did not enter their weight in the device this show that our data in incomplete and inconsistent

Do the same with user with the minimum heartrate records

## Check which individual has min heart rate

DailyHr_records[which.min(DailyHr_records$Hraterecords_in_a_Day),]
## # A tibble: 1 × 3
##           Id Date       Hraterecords_in_a_Day
##        <dbl> <date>                     <dbl>
## 1 6775888955 2016-04-29                  1198

Check user “6775888955” data entry accuracy in heartrate_seconds_merged

user_6775888955 <-heartrate_seconds_merged[heartrate_seconds_merged$Id == "6775888955" ,]

Conclusion:User get their heart rate between 5 to 25 seconds on average that’s why they the minimum records

Check users BMI and weight

Id_BMI_Weight[Id_BMI_Weight$Id == "6775888955",]
## # A tibble: 0 × 3
## # ℹ 3 variables: Id <dbl>, WeightKg <dbl>, BMI <dbl>

Conclusion: No such user in the ‘weightLogInfo_merged’, this is to show that user did not enter their weight in the device this show that our data in incomplete and inconsistent