---
title: "Digital Screentime and Mental Well-Being"
author: Your Name Here
format:
  html:
    df-print: kable
    theme: cosmo
    toc: true
    toc-depth: 3
    embed-resources: true
execute:
  echo: true
  editor: source
---

# Getting started

In order to run this script, you will need to first [download the data](https://osf.io/49rmq/files/osfstorage/5846cc6f9ad5a101fed9a052) from OSF. Look for the download symbol in the upper right-hand side of the webpage. Save it to the project directory containing this script.

You will also want to download the corresponding [paper](https://doi.org/10.1177/0956797616678438).

More information about the `screentime` dataset can be found on the course website [here](https://ritcheym.github.io/dataskills/datasets/screentime.html).

```{r message=FALSE, warning=FALSE, echo=FALSE}
library(tidyverse)
```

# Load data

```{r}
df <- read_csv('data.csv')
```

# Process data

Select to keep only the columns that we are going to consider. Filter to keep only the rows that have data for well-being scores and aggregate screentime measures.

```{r}
df <- df |>
  select(mwbi,male,minority,deprived,weekday_screen,weekend_screen,
         watch_wd,watch_we,play_wd,play_we,comp_wd,comp_we,sp_wd,sp_we) |>
  filter(!is.na(mwbi) & !is.na(weekday_screen) & !is.na(weekend_screen)) 
```

# Get to know your data!

## Use the commands that you've learned about to explore a dataset

```{r}
# FILL IN YOUR CODE HERE
```

## What variables are there? What data types are they?

WRITE A SUMMARY HERE

## How many rows and columns are there?

```{r}
# FILL IN YOUR CODE HERE TO CALCULATE
```

Add in-line Markdown HERE to say how many rows and columns there are.

## Calculate the following summary statistics for the mental wellbeing index (MWBI): mean, minimum, maximum.

```{r}
# FILL IN YOUR CODE HERE
# Hint: you can use the $ operator to access the mwbi column
```

# Counting data

## Count the number of participants included from different demographic subsets.

```{r}
# FILL IN YOUR CODE HERE
```

## What percentage of the sample is male?

```{r}
# FILL IN YOUR CODE HERE
```

# Summarize the data

## Calculate the mean MWBI for different demographic subsets.

```{r}
# FILL IN YOUR CODE HERE
```

## Create a new variable called `screen_avg` that averages together weekday and weekend screentime, using the `mutate` function.

```{r}
# FILL IN YOUR CODE HERE
```

## Now calculate the summary statistics for your new `screen_avg` variable.

```{r}
# FILL IN YOUR CODE HERE
```

Do you notice any patterns in the data? If so, DESCRIBE THEM HERE.

# Data Visualization

Your goal is to use ggplot to recreate parts of Figures 1 and 2 from this paper. I'll include some code below to help you get going with it.

The paper can be found here: <https://journals.sagepub.com/doi/10.1177/0956797616678438>

## Recreate Figure 1A

You will recreate panel A from Figure 1 (the top left panel).

For this plot, we need the mental well-being measure (here, `mwbi`) and the screentime measures for each type of screentime, split by screentime type and weekday vs weekend

In practical terms, this involves making the data "tidy" by converting the dataframe from its current wide format into long format. We want to gather the screentime variables and create new variables that index the day type (weekday or weekend) as well as the screentime type (watch, play, computer, smartphone).

### Tidy the data

Because the different screentime measures are in different columns, we need to gather them together into a single column-- in other words, we need to make our data tidy.

To do so, we will use the `pivot_longer` command, which is designed to convert wide data to long data. We'll talk more about this function later in the class.

```{r}
# use the pivot_longer function to gather the variables
df.tidy <- df |>
  pivot_longer(
    cols = c(watch_wd, play_wd, comp_wd, sp_wd, watch_we, play_we, comp_we, sp_we),         
    names_to = "type_day",       
    values_to = "screentime"
  )

# clean up the resulting dataframe
df.tidy <- df.tidy |>
  select(male, minority, deprived, mwbi, type_day, screentime) |>
  filter(!is.na(screentime))
```

This gets us most of the way there, but it'd be nice to have additional variables that separate out the screentime type from the day. Let's create those next.

### Recode the variables

```{r}
# use the separate function to separate the type_day variable into two
df.tidy <- df.tidy |>
  separate(col = type_day, into = c("type", "day"), sep = "_")

# finally, turn type, day, and male into factors, which will be useful for plotting
df.tidy$male <- factor(df.tidy$male)
df.tidy$type <- factor(df.tidy$type,levels=c("watch","play","comp","sp"))
df.tidy$day <- factor(df.tidy$day)
```

### Calculate the summary statistics

Finally, we need to calculate the summary statistics that will go into our plot, including the means and the 95% confidence intervals for each combination of conditions.

Make sure you can read and understand this code!

```{r}
# average data
df.tidy.avg_mwbi <- df.tidy |>
  group_by(type,day,screentime) |>
  summarize(mwbi_avg = mean(mwbi,na.rm=TRUE),
            mwbi_se = sd(mwbi,na.rm=TRUE) / sqrt(n()),
            mwbi_ci_lower = mwbi_avg - 1.96 * mwbi_se,
            mwbi_ci_upper = mwbi_avg + 1.96 * mwbi_se)

# take a peek at the first 6 rows
head(df.tidy.avg_mwbi)
```

The `df.tidy.avg_mwbi` dataframe contains all of the data that we will use to reproduce Figure 1.

### Plot the data

To plot only panel A, you might want to first filter the data to include time spent watching TV and movies.

```{r}
df_fig1a <- df.tidy.avg_mwbi |>
  filter(type=="watch")
```

Now plot!

```{r}
# ADD YOUR CODE FOR FIGURE 1A HERE
```

**Bonus challenge (optional):** Plot all 4 panels of Figure 1 by using the `facet_wrap` function. You will use `df.tidy.avg_mwbi` for your plot.

```{r}

```

**Extra bonus challenge (optional):** Try to adjust the style and theme settings to make the plot look as similar as possible to the published version.

```{r}

```

## Reproduce Figure 2A

You will recreate panel A from Figure 1 (the top panel).

For this plot, we can use the `df.tidy` variable that we created before. But this time, we need to average the screentime measures for each type of screentime, separately for weekdays and weekend days, and separately for males and females.

### Calculate the summary statistics

First we calculate the summary statistics that will go into our plot, including the means and confidence intervals for each combination of conditions.

Make sure you can read and understand this code!

```{r}
# average data
df.tidy.avg_screen <- df.tidy |>
  group_by(male,type,day) |>
  summarize(screen_avg = mean(screentime,na.rm=TRUE),
            screen_se = sd(screentime,na.rm=TRUE) / sqrt(n()),
            screen_ci_lower = screen_avg - 1.96 * screen_se,
            screen_ci_upper = screen_avg + 1.96 * screen_se)

# take a peek at the first 6 rows
head(df.tidy.avg_screen)
```

The `df.tidy.avg_screen` dataframe contains all of the data that we will use to reproduce Figure 2.

### Plot the data

To plot only panel A, you might want to first filter the data to include weekday screentime measures.

```{r}
df_fig2a <- df.tidy.avg_screen |>
  filter(day=="wd")
```

Now plot!

```{r}
# ADD YOUR CODE FOR FIGURE 2A HERE
```

**Bonus challenge (optional):** Plot both panels of Figure 2 by using the `facet_wrap` function. You will use `df.tidy.avg_screen` for your plot.

```{r}

```

**Extra bonus challenge (optional):** Try to adjust the style and theme settings to make the plot look as similar as possible to the published version.

```{r}

```
