Project 2

Author

Andreas Sanches

Project 2 - Sleep quality

The “Sleep Quality” dataset deals with indicators and aspects of 374 individuals’ sleep quality. Among the variables, we have 6 categorical variables, that are the “person ID,” “gender,” “Occupation,” “Blood Pressure”, “BMI Category” (The BMI category of the person (e.g., Underweight, Normal, Overweight), and “Sleep Disorder” (The presence or absence of a sleep disorder in the person (None, Insomnia, Sleep Apnea)).We then have 7 quantitative variables, which are “age,” “sleep duration” (The number of hours the person sleeps per day.), “quality of sleep (scale 1-10)” (A subjective rating of the quality of sleep, ranging from 1 to 10.), “physical activity level” ((minutes/day): The number of minutes the person engages in physical activity daily.), “stress level (scale: 1-10)”(A subjective rating of the stress level experienced by the person, ranging from 1 to 10.), “heart rate -bpm” (The resting heart rate of the person in beats per minute.), “Daily Steps” (The number of steps the person takes daily.).

  1. As an athlete and enthusiast of a healthy lifestyle, I understood the importance of a good sleep night. Poor sleep habits can lead to the rise of short- and long-term diseases and consequently shorten individuals’ lives. That said, I want to see the relation between the quality of sleep, and sleep duration variables and whether they are associated with the BMI categories of the individuals.

*Warning: this dataset is synthetic and it was created for illustrative purposes. According to the author, “It does not originate from any specific individual or external source”


## Open and load the packages

::: {.cell}

```{.r .cell-code}
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ 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(highcharter)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
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

:::

Load the directory

setwd("/Users/andreassanches/Documents")
sleep_quality <- read_csv("Sleep_health_and_lifestyle_dataset 2.csv")
Rows: 374 Columns: 13
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (5): Gender, Occupation, BMI Category, Blood Pressure, Sleep Disorder
dbl (8): Person ID, Age, Sleep Duration, Quality of Sleep, Physical Activity...

ℹ 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.
head(sleep_quality)
# A tibble: 6 × 13
  `Person ID` Gender   Age Occupation        `Sleep Duration` `Quality of Sleep`
        <dbl> <chr>  <dbl> <chr>                        <dbl>              <dbl>
1           1 Male      27 Software Engineer              6.1                  6
2           2 Male      28 Doctor                         6.2                  6
3           3 Male      28 Doctor                         6.2                  6
4           4 Male      28 Sales Representa…              5.9                  4
5           5 Male      28 Sales Representa…              5.9                  4
6           6 Male      28 Software Engineer              5.9                  4
# ℹ 7 more variables: `Physical Activity Level` <dbl>, `Stress Level` <dbl>,
#   `BMI Category` <chr>, `Blood Pressure` <chr>, `Heart Rate` <dbl>,
#   `Daily Steps` <dbl>, `Sleep Disorder` <chr>

Replacing the varibale “Normal” with “Normal Weight” and other variables

To make it clearer when I create the visualization

# Replace "Normal" with "Normal Weight" in the "BMI Category" column
sleep_quality <- sleep_quality |>
  mutate(`BMI Category` = ifelse(`BMI Category` == "Normal", "Normal Weight", `BMI Category`))
sleep_quality <- sleep_quality |>
  rename(
    quality_of_sleep = "Quality of Sleep",
    stress_level = "Stress Level",
    BMI_category = "BMI Category",
    sleep_duration = "Sleep Duration",
    heart_rate_bpm = "Heart Rate"
  )

There is no missing data in the “sleep_quality” dataset!

I used this code to make sure that there is no missing values in the dataset.

sum(is.na(sleep_quality))
[1] 0

Creating visualizations (Histogram and Boxplot)

Histogram for quality_of_sleep X count. We can see from the histogram generated, with the distributions stacked on each other, that in sleep qualities of 6 and 8, there’s a big difference between the categories; as I imagined, the majority of individuals who don’t have a good sleep quality (6), are overweight. On the other hand, from the sleep quality 7 to beyond, normal-weight individuals report having good sleep quality. Also, we can see a predominance of normal weight individuals reporting a sleep quality 8 on the scale. I created a histogram to emphasize and see the output of the “Quality of Sleep” and Count relation.

ggplot(sleep_quality, aes(x = quality_of_sleep, fill = BMI_category)) +
  geom_histogram(color = "black", bins = 25, alpha = 0.7) +
   labs (title = "Quality of Sleep Histogram", x = "Quality of Sleep (Scale 1-10)", y = "Count", fill = "BMI Category", caption = "Synthetically generated") +
  theme_minimal()

Now, I added an interactivity feature to my visualization. Now it’s even easier to see the relation between the number of individuals per BMI category and its sleep quality.

# Convert to plotly with colors based on "BMI category"
plotly_of_histogram <- plot_ly(
  data = sleep_quality,
  x = ~quality_of_sleep,
  color = ~BMI_category,
  type = "histogram",
  bins = 25) |>
  layout(
    title = "Quality of Sleep Histogram - Interactivity",
    xaxis = list(title = "Quality of Sleep (Scale 1-10)"),
    yaxis = list(title = "Count"),
    showlegend = TRUE,
    caption = "Synthetically generated")

plotly_of_histogram
Warning: 'layout' objects don't have these attributes: 'caption'
Valid attributes include:
'_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'
Warning: 'histogram' objects don't have these attributes: 'bins'
Valid attributes include:
'_deprecated', 'alignmentgroup', 'autobinx', 'autobiny', 'bingroup', 'cliponaxis', 'constraintext', 'cumulative', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'histfunc', 'histnorm', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'insidetextanchor', 'insidetextfont', 'legendgroup', 'legendgrouptitle', 'legendrank', 'marker', 'meta', 'metasrc', 'name', 'nbinsx', 'nbinsy', 'offsetgroup', 'opacity', 'orientation', 'outsidetextfont', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textangle', 'textfont', 'textposition', 'textsrc', 'texttemplate', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'xaxis', 'xbins', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'yaxis', 'ybins', 'ycalendar', 'yhoverformat', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'histogram' objects don't have these attributes: 'bins'
Valid attributes include:
'_deprecated', 'alignmentgroup', 'autobinx', 'autobiny', 'bingroup', 'cliponaxis', 'constraintext', 'cumulative', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'histfunc', 'histnorm', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'insidetextanchor', 'insidetextfont', 'legendgroup', 'legendgrouptitle', 'legendrank', 'marker', 'meta', 'metasrc', 'name', 'nbinsx', 'nbinsy', 'offsetgroup', 'opacity', 'orientation', 'outsidetextfont', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textangle', 'textfont', 'textposition', 'textsrc', 'texttemplate', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'xaxis', 'xbins', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'yaxis', 'ybins', 'ycalendar', 'yhoverformat', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'histogram' objects don't have these attributes: 'bins'
Valid attributes include:
'_deprecated', 'alignmentgroup', 'autobinx', 'autobiny', 'bingroup', 'cliponaxis', 'constraintext', 'cumulative', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'histfunc', 'histnorm', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'insidetextanchor', 'insidetextfont', 'legendgroup', 'legendgrouptitle', 'legendrank', 'marker', 'meta', 'metasrc', 'name', 'nbinsx', 'nbinsy', 'offsetgroup', 'opacity', 'orientation', 'outsidetextfont', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textangle', 'textfont', 'textposition', 'textsrc', 'texttemplate', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'xaxis', 'xbins', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'yaxis', 'ybins', 'ycalendar', 'yhoverformat', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Boxplot for sleep_duration by BMI_category. In this case, even though it seems a little redundant (the legend and the box plot colors), I was interested in seeing if the different BMI categories’ sleep duration is somehow related. As I mentioned, from common sense healthy people don’t face disorders as commonly as unhealthy people, and as a result, they tend to sleep more and better. After creating the plot, I concluded that normal weight individuals also tend to sleep more. In contrast, despite the variations, obese and overweight sleep less, which might be a consequence of their health situation. I created a boxplot and differentiated the categories using different colors. It’s also important to notice that both normal weight and overweight individuals, have outliers.

ggplot(sleep_quality, aes(x = BMI_category, y = sleep_duration, fill = BMI_category)) +  labs (title = "BMI Category x Sleep Duration (Avg Per Day)", x = "BMI Category", y = "Sleep Duration", fill = "BMI Category", caption = "Synthetically generated") +
  geom_boxplot() +
  theme_minimal()

The multiple regression models is defined using the ‘lm’ function.

m_r_line <- lm(quality_of_sleep ~ sleep_duration + BMI_category, data = sleep_quality)

summary(m_r_line)

Call:
lm(formula = quality_of_sleep ~ sleep_duration + BMI_category, 
    data = sleep_quality)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.66976 -0.19278  0.09248  0.33024  1.06753 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
(Intercept)            -2.29252    0.28834  -7.951 2.27e-14 ***
sleep_duration          1.34427    0.03870  34.737  < 2e-16 ***
BMI_categoryObese      -0.66359    0.17882  -3.711 0.000238 ***
BMI_categoryOverweight  0.09011    0.06341   1.421 0.156185    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5504 on 370 degrees of freedom
Multiple R-squared:  0.7902,    Adjusted R-squared:  0.7885 
F-statistic: 464.6 on 3 and 370 DF,  p-value: < 2.2e-16

Quality of Sleep Prediction

Each point of the scatterplot represents an observation. The X-Axis represents the predicted values of the dependent variable (quality_of_sleep). The Y-Axis represents the actual values of the dependent variable (quality_of_sleep) from my dataset. The values of the X-Axys are calculated by applying the estimated coefficients from the multiple regression model to the observed values of the independent variables. I got the predicted values by using the function “fitted”.

sleep_quality$fitted_values <- fitted(m_r_line)

scatter_plot <- plot_ly(data = sleep_quality,
  x = ~fitted_values,
  y = ~quality_of_sleep,
  color = ~BMI_category,
  type = "scatter",
  mode = "markers",
  text = ~paste("BMI Category: ", BMI_category, "<br>Sleep Duration: ", sleep_duration),
  marker = list(size = 10)) |>
  layout( title = "Quality of Sleep Prediction",
    xaxis = list(title = "Predicted Quality of Sleep"),
    yaxis = list(title = "Quality of Sleep (Actual)"),
    showlegend = TRUE,
    caption = "Synthetically generated")

scatter_plot
Warning: 'layout' objects don't have these attributes: 'caption'
Valid attributes include:
'_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'

Essay (Parts “b” & “c”)

  1. I searched for information on Google to see studies that explore the variables I analyzed in the dataset. I found one, called “Sleep duration, sleep quality and body weight: Parallel developments,” led by Dr. Gonnissen and his team, which reports that in childhood, “the increase in obesity has developed over the same period as the progressive decrease in self-reported sleep duration”. This affirmation shows the inverse relationship between these 2 variables I have in my dataset. The author claims that in adulthood, the relationship remains the same. Furthermore, the researchers reported that excessive weight loss BMI and fat mass decrease, are also related to higher sleep durations. The study then concluded that a diet seeking weight loss and successive body-weight maintenance contributes to better sleep quality.
    https://pubmed.ncbi.nlm.nih.gov/23643826/

  2. The first two visualizations (a boxplot and histogram) basically compared the quality of sleep per BMI (which showed that usually normal-weight individuals have a better sleep quality in comparison with obese and overweight individuals), and the BMI category per sleep duration (which showed normal weight individuals sleep more than obese and overweight individuals). The third visualization, a scatter plot, allows us to compare the predicted sleep quality against the actual observed sleep quality (which shows, once again, that the sleep quality of normal-weight individuals tends to be better than the other 2 groups).