---
title: "R Workshop 3: A Research Workflow from Start to Finish"
subtitle: "Student workbook · synthetic campus survey"
format:
  html:
    toc: true
    toc-depth: 2
execute:
  echo: true
  warning: false
  message: false
---

## Today's goal

In this final workshop we will put together all the skills we've learned so far. By the end, you will have imported the data, made a small demographics summary table, calculated scores for a four-item measure, visualized and summarized it, and described a sample correlation. You will finish with a short, reproducible report---something close to a workflow you might use as a research assistant.

Demonstration chunks run when the document renders. Practice chunks have `#| eval: false`, so incomplete work will not break your document. Run those chunks interactively as you work. Once a practice chunk is correct and you want its output in your final HTML, delete its `#| eval: false` line.

## 1. Open the project and meet the new data

Open `R-Workshop-1.Rproj`, then open this `.qmd` in RStudio. The CSV is in the `data` folder next to the earlier workshop data. The project gives us a reliable starting point for the relative path below.

```{r}
library(tidyverse)
dat <- read_csv("data/workshop3_campus_survey.csv")
glimpse(dat)
```

Each row is one synthetic respondent. The `id` column identifies a row; it is not a score or an outcome.

```{r}
nrow(dat)
ncol(dat)
names(dat)
```

| Column | Meaning |
|---|---|
| `age` | Age in years; a few values are missing |
| `gender` | Self-described gender category; use counts, not averages |
| `year_in_school` | Year category |
| `first_generation` | First-generation college student response |
| `study_hours_week` | Approximate study hours in a week |
| `belonging_1` to `belonging_4` | Four positively worded campus-belonging items, each 1–5 |
| `social_confidence` | A separate 1–5 self-rating; a few values are missing |

### Your turn: inspect one column

Copy the `count()` pattern below, replacing `year_in_school` with `first_generation`. The pipe `|>` means “then pass the result to the next step.” To insert it in RStudio: **Windows: Ctrl+Shift+M**; **Mac: Shift+Command+M**.

```{r}
dat |>
  count(year_in_school)
```

```{r}
#| eval: false
# Copy and adapt the count() pipeline here.
```

What do you notice about the categories? **[Write one sentence here.]**

## 2. Build a demographics summary

A demographics table usually reports **counts and percentages** for categories and a suitable summary for age. We will build small pieces first. A percentage answers “what share of all 200 rows is this category?”

```{r}
dat |>
  count(year_in_school) |>
  mutate(percent = round(100 * n / sum(n), 1))
```

Notice that `n` is created by `count()`. We then calculate a new `percent` column with `mutate()`.

### Your turn: count gender categories

Copy and adapt the previous pipeline to show `gender`, `n`, and `percent`. Keep every category, including “Prefer not to answer.” Long labels are easier to read in a table than in a cramped plot.

```{r}
#| eval: false
# Paste the count-and-percent pipeline here; change the category column.
```

Some gender categories have very small counts. Report the counts respectfully; do not make group comparisons or treat a tiny category estimate as stable.

### Age and missing values

`is.na()` marks a missing value. This check tells us how many ages are available before we calculate a mean.

```{r}
sum(is.na(dat$age))
```

```{r}
dat |>
  summarize(
    age_n = sum(!is.na(age)),
    age_mean = round(mean(age, na.rm = TRUE), 1),
    age_sd = round(sd(age, na.rm = TRUE), 1),
    age_min = min(age, na.rm = TRUE),
    age_max = max(age, na.rm = TRUE)
  )
```

The `age_n` value is the number of nonmissing ages, not the full row count. `na.rm = TRUE` means “remove missing values for this calculation.”

### Your turn: one more demographic category

Fill in the blank to count and calculate percentages for `first_generation`.

```{r}
#| eval: false
dat |>
  count(_____) |>
  mutate(percent = round(100 * n / sum(n), 1))
```

Write two sentences for a demographics paragraph. Include the total sample size, one category count or percentage, and the age mean and SD. Say “in this synthetic sample,” not “at the university.” **[Write here.]**

## 3. Score a short measure

Researchers often combine several survey items into one score. Here, all four `belonging_` items run in the same direction: **1 means lower belonging and 5 means higher belonging**. For this *teaching example*, each person's `belonging_mean` is the average of the items they answered. Everyone answered at least three of four. A real questionnaire may have reverse-coded items and a different missing-data rule; follow its scoring instructions rather than copying this rule automatically.

First check the four item columns:

```{r}
dat |>
  select(id, starts_with("belonging_")) |>
  slice_head(n = 6)
```

We can select those four columns with their names and average them **across each row**. `rowMeans()` is a base R function; `na.rm = TRUE` allows an average when one item is missing.

```{r}
item_names <- c("belonging_1", "belonging_2", "belonging_3", "belonging_4")
dat <- dat |>
  mutate(belonging_mean = rowMeans(dat[item_names], na.rm = TRUE))
```

Check the score against the original items. The first score should equal the mean of that person's available answers.

```{r}
dat |>
  select(id, all_of(item_names), belonging_mean) |>
  slice_head(n = 6)
```

```{r}
summary(dat$belonging_mean)
sum(is.na(dat$belonging_mean))
```

### Your turn: check the scoring rule

Fill in the blank to count how many belonging items each person answered, then count the results. You should see only 3 and 4—not 0, 1, or 2.

```{r}
#| eval: false
dat |>
  mutate(items_answered = rowSums(!is.na(dat[_____)])) |>
  count(items_answered)
```

Why might averaging available answers be better than replacing one missing item with zero? **[Write one sentence here.]**

## 4. Visualize, then summarize the score

Look at the shape of the scores before reducing them to a few numbers.

```{r}
ggplot(data = dat, aes(x = belonging_mean)) +
  geom_histogram(binwidth = 0.25, boundary = 1, color = "white", fill = "steelblue") +
  scale_x_continuous(breaks = 1:5) +
  labs(
    title = "Campus-belonging scores in the synthetic sample",
    x = "Mean of four belonging items (1–5)",
    y = "Number of respondents"
  ) +
  theme_minimal()
```

Where are most scores? Do you see a long tail or a roughly symmetric shape? **[Write here.]**

```{r}
dat |>
  summarize(
    n = sum(!is.na(belonging_mean)),
    mean = round(mean(belonging_mean, na.rm = TRUE), 2),
    median = round(median(belonging_mean, na.rm = TRUE), 2),
    sd = round(sd(belonging_mean, na.rm = TRUE), 2),
    minimum = min(belonging_mean, na.rm = TRUE),
    maximum = max(belonging_mean, na.rm = TRUE)
  )
```

The mean and median summarize center; the SD and range summarize spread. These numbers are a compact description of the distribution you just saw, not a replacement for the graph.

### Your turn: transfer the pattern

Copy the histogram and summary patterns to describe `study_hours_week`. Change the histogram's bin width to `2`, give it suitable labels, and calculate its nonmissing `n`, mean, median, and SD.

```{r}
#| eval: false
# Paste and adapt a histogram here.
```

```{r}
#| eval: false
# Paste and adapt a summarize() pipeline here.
```

## 5. Describe a relationship—without inference

Does the belonging score tend to be higher when `social_confidence` is higher **among these synthetic respondents**? Start with a scatterplot. Because item means take only a limited set of values, some points overlap; transparency helps us see crowded areas.

```{r}
ggplot(data = dat, aes(x = belonging_mean, y = social_confidence)) +
  geom_point(alpha = 0.45, color = "darkorange", na.rm = TRUE) +
  labs(
    title = "Belonging and social confidence in the synthetic sample",
    x = "Mean belonging score (1–5)",
    y = "Social confidence (1–5)"
  ) +
  theme_minimal()
```

Look for direction, approximate form, strength, and unusual points. **[Write one sentence about the scatterplot here.]**

A correlation, `r`, summarizes the **linear** association between two numeric variables. It ranges from −1 to +1. Positive values mean the variables tend to rise together; negative values mean one tends to fall as the other rises; values near zero mean little linear association. There are no universal cutoffs for “weak” or “strong,” so use the scatterplot too.

```{r}
paired_n <- sum(complete.cases(dat[c("belonging_mean", "social_confidence")]))
paired_n
cor(dat$belonging_mean, dat$social_confidence, use = "complete.obs")
```

`use = "complete.obs"` uses only rows with **both** values present. Report that paired `n` alongside the correlation. This calculation is descriptive: it is not a significance test, does not establish causation, and does not tell us what would happen in a real population.

### Your turn: a second descriptive correlation

Make a scatterplot of `study_hours_week` (horizontal axis) and `belonging_mean` (vertical axis). Then calculate their correlation. It may be much closer to zero. Describe what you see, even if the pattern is weak.

```{r}
#| eval: false
# Copy and adapt the scatterplot above.
```

```{r}
#| eval: false
cor(dat$_____, dat$_____, use = "complete.obs")
```

**[Write one sentence about direction and strength in this synthetic sample. Do not make a causal or population claim.]**

## 6. Put it together: a compact research report

Use your results above to write a short report below. Keep it descriptive and specific. You may paste your working code into the practice chunks so the `.qmd` stores every step you want to reuse. Code entered only in the Console will not run when this document is rendered from a fresh session.

### Sample and demographics

Report total `N`; give counts and percentages for `year_in_school` or `first_generation`; report mean age, SD, and nonmissing age `n`.

**[Write 2–3 sentences here.]**

### Measure and distribution

State what the four items measure, how the mean score was calculated, its range, and what the histogram and summary show.

**[Write 2–3 sentences here.]**

### Descriptive relationship

Report the direction, approximate strength, correlation (rounded to two decimals), and paired `n` for belonging and social confidence. Say that this is a descriptive association in synthetic data and does not imply causation or a wider-population effect.

**[Write 2–3 sentences here.]**

### Final check and render

Save: **Windows: Ctrl+S**; **Mac: Command+S**. Render: click **Render**, or use **Windows: Ctrl+Shift+K** / **Mac: Shift+Command+K**. Open `workshop3_student.html` if the preview does not appear. If you want completed practice output in the HTML, first remove `#| eval: false` from those chunks and render again.

Your finished `.qmd`, its HTML, and the CSV form a portable record of the work. Keep the folder structure intact so the relative path continues to work.
