Instructions

This is your week 1 checkpoint. It pulls together everything we covered: identifying data types, loading and graphing data in base R, using ggplot2 with filter(), mutate(), and color, and thinking carefully about bias, sampling, and experimental design.

Part A uses R. Part B is written reasoning — no code required, just clear thinking and complete sentences. Answer directly in this document, in the spots marked ANSWER:.


Part A: Working With Data in R

We’re going to use a new dataset called msleep — it has sleep data for 83 different mammal species.

library(tidyverse)
data(msleep)
head(msleep)
## # A tibble: 6 × 11
##   name    genus vore  order conservation sleep_total sleep_rem sleep_cycle awake
##   <chr>   <chr> <chr> <chr> <chr>              <dbl>     <dbl>       <dbl> <dbl>
## 1 Cheetah Acin… carni Carn… lc                  12.1      NA        NA      11.9
## 2 Owl mo… Aotus omni  Prim… <NA>                17         1.8      NA       7  
## 3 Mounta… Aplo… herbi Rode… nt                  14.4       2.4      NA       9.6
## 4 Greate… Blar… omni  Sori… lc                  14.9       2.3       0.133   9.1
## 5 Cow     Bos   herbi Arti… domesticated         4         0.7       0.667  20  
## 6 Three-… Brad… herbi Pilo… <NA>                14.4       2.2       0.767   9.6
## # ℹ 2 more variables: brainwt <dbl>, bodywt <dbl>

A1. Identify the data types

Run this to see every column name and what type R thinks it is:

str(msleep)
## tibble [83 × 11] (S3: tbl_df/tbl/data.frame)
##  $ name        : chr [1:83] "Cheetah" "Owl monkey" "Mountain beaver" "Greater short-tailed shrew" ...
##  $ genus       : chr [1:83] "Acinonyx" "Aotus" "Aplodontia" "Blarina" ...
##  $ vore        : chr [1:83] "carni" "omni" "herbi" "omni" ...
##  $ order       : chr [1:83] "Carnivora" "Primates" "Rodentia" "Soricomorpha" ...
##  $ conservation: chr [1:83] "lc" NA "nt" "lc" ...
##  $ sleep_total : num [1:83] 12.1 17 14.4 14.9 4 14.4 8.7 7 10.1 3 ...
##  $ sleep_rem   : num [1:83] NA 1.8 2.4 2.3 0.7 2.2 1.4 NA 2.9 NA ...
##  $ sleep_cycle : num [1:83] NA NA NA 0.133 0.667 ...
##  $ awake       : num [1:83] 11.9 7 9.6 9.1 20 9.6 15.3 17 13.9 21 ...
##  $ brainwt     : num [1:83] NA 0.0155 NA 0.00029 0.423 NA NA NA 0.07 0.0982 ...
##  $ bodywt      : num [1:83] 50 0.48 1.35 0.019 600 ...

ANSWER: Pick four columns from msleep (try to get a mix). For each one, write the column name and identify it as categorical or numeric. If numeric, also say whether it’s discrete or continuous. If categorical, also say whether it’s ordinal or nominal.

  • Column 1: name|categorical|nominal
  • Column 2: sleep_total|numeric|continuous
  • Column 3: bodywt|numeric|continuous
  • Column 4: vore|categorical|nominal

A2. Load and inspect

# What are the unique values of the of the vore variable? 
unique(msleep$vore)
## [1] "carni"   "omni"    "herbi"   NA        "insecti"

ANSWER: How many different types of vore are represented in this dataset? 5 including NA ### A3. Base R graphs

Make one graph of a numeric variable and one graph of a categorical variable, using base R (no ggplot yet). Make them nice!!!

# Numeric variable: choose one and make an appropriate graph
hist(msleep$sleep_total,
     main = "Mammalian sleep",
     xlab = "Total sleep (hours)",
     ylab = "Number of species",
     col = "#4C9BE0",
     border = "white",
     breaks = 12)

# Categorical variable: choose one and make an appropriate graph
barplot(table(msleep$vore),
        main = "Mammal diet types",
        xlab = "Diet (vore)",
        ylab = "Number of species",
        col = c("#66C2A5", "#FC8D62", "#8DA0CB", "#E78AC3"),
        border = "white")

ANSWER: The sleep histogram is mound-shaped and roughly symmetric, with most species sleeping between about 8 and 14 hours and a center near 10. The diet barplot is uneven: herbivores are the largest group, omnivores and carnivores are close behind, and insectivores are rare.

A4. filter() and a ggplot

The vore column tells you what each mammal eats: "carni", "herbi", "omni", or "insecti". Some rows have NA (missing data).

# Filter msleep to keep only herbivores ("herbi")
herbivores <- filter(msleep, vore == "herbi")

# Make a scatterplot of bodywt (x) vs sleep_total (y) using herbivores only
# (body weight is hugely skewed, so a log x-axis spreads the points out)
ggplot(data = herbivores, aes(x = bodywt, y = sleep_total)) +
  geom_point(color = "#FC8D62", size = 3, alpha = 0.8) +
  scale_x_log10() +
  labs(title = "Body weight vs. sleep in herbivores",
       x = "Body weight (kg, log scale)",
       y = "Total sleep (hours)") +
  theme_minimal()

A5. mutate() and color

# Create a new column called sleep_pct: what % of each day is spent sleeping
# (hint: there are 24 hours in a day)
msleep_pct <- mutate(msleep, sleep_pct = sleep_total / 24 * 100)

# Plot bodywt (x) vs sleep_pct (y), colored by vore
ggplot(data = msleep_pct, aes(x = bodywt, y = sleep_pct, color = vore)) +
  geom_point(size = 3, alpha = 0.8) +
  scale_x_log10() +
  scale_color_brewer(palette = "Set2", na.value = "grey70") +
  labs(title = "Body size vs. share of day asleep",
       x = "Body weight (kg, log scale)",
       y = "Percent of day asleep",
       color = "Diet") +
  theme_minimal()

ANSWER: Looking at your colored plot, does one diet category (vore) seem to stand out from the others in any way? Describe what you see.

On a log scale for body weight, there’s a clear downward trend: heavier mammals tend to spend a smaller share of the day asleep. Herbivores stretch across the whole size range and include the giant, low-sleeping animals like elephants. Insectivores sit near the top, sleeping the largest percentage of the day.

A6. Your choice

Make one more ggplot using msleep that uses at least one of filter() or mutate(), and at least one of color or fill. Choose your own variables — this one isn’t filled in for you.

# Does diet relate to how long a mammal sleeps?
msleep %>%
  filter(!is.na(vore)) %>%
  ggplot(aes(x = vore, y = sleep_total, fill = vore)) +
  geom_boxplot(alpha = 0.85) +
  scale_fill_brewer(palette = "Set2") +
  labs(title = "Sleep by diet type",
       x = "Diet (vore)",
       y = "Total sleep (hours)",
       fill = "Diet") +
  theme_minimal()

ANSWER: I wanted to see whether diet relates to how long a mammal sleeps. Insectivores have by far the highest median sleep, close to 18 hours, though there are only five of them. The other three diets cluster near 10 hours: omnivores are the most tightly grouped, while carnivores and herbivores both spread out widely, from species that barely sleep to ones that sleep a lot. So diet is related to sleep, but it’s far from the whole story.

A7. Summary Statistics

# Calculate the average body weight (the answer should not be NA!)
mean(msleep$bodywt, na.rm = TRUE)
## [1] 166.1363
# Calculate the standard deviation of body weight.(the answer should not be NA!)
sd(msleep$bodywt, na.rm = TRUE)
## [1] 786.8397
# Calculate the five number summary of awake
fivenum(msleep$awake)
## [1]  4.10 10.25 13.90 16.15 22.10

Part B: Bias, Sampling, and Study Design

Read both scenarios below and answer the questions that follow in your own words, in complete sentences. There’s no code in this section.

Scenario 1: Breakfast and Math Scores

A school district wants to know if students who eat breakfast perform better on math tests. Researchers survey 200 students at one elementary school, asking each student whether they ate breakfast that morning and recording their most recent math test score. Students who report eating breakfast have an average score 8 points higher than students who report not eating breakfast. A local news headline reads: “Eating Breakfast Causes Higher Math Scores, Study Finds.”

B1. What is the explanatory variable in this study? What is the response variable?

ANSWER: The explanatory variable is whether a student ate breakfast that morning. The response variable is the student’s most recent math test score.

B2. Is this an observational study or an experiment? How can you tell?

ANSWER: It’s an observational study. The researchers only surveyed and recorded what students already did. They never assigned anyone to eat or skip breakfast, so there is no treatment or control group.

B3. Name two potential confounding variables — something else that could affect both breakfast-eating and math scores. Explain your reasoning.

ANSWER: Family income is one. Higher-income families can more reliably provide breakfast and also things like tutoring and a stable home, which raise scores. Morning routine and sleep is another. A child with a steady routine is more likely to wake up with time to eat and to arrive rested and focused. Both factors push on breakfast and on test scores at the same time.

B4. Is the news headline’s cause-and-effect claim justified by this study? Why or why not?

ANSWER: No. This is an observational study with obvious confounders, so it can only show that breakfast and scores are associated, not that one causes the other. The headline claims a cause-and-effect link the data cannot support.

B5. Describe the sampling method likely used here (how do you think the 200 students were chosen?). Is this sample likely to generalize to all elementary students everywhere? Why or why not?

ANSWER: It looks like a convenience sample. All 200 students come from one elementary school, probably whoever was easy to survey. That school reflects a single neighborhood’s income level and demographics, so the results are unlikely to generalize to all elementary students everywhere.

B6. Redesign it. Briefly describe a different sampling method that would produce a sample more representative of elementary students in general. Name the method and explain why it’s an improvement.

ANSWER: A stratified random sample would be better. Split the population into groups (by region or income level, for example) and randomly select students within each group. It draws from many schools instead of one, so the sample mirrors the variety in the real population and the results generalize better.


Scenario 2: Ice Cream and Drowning

For many years, researchers have noted a strong positive correlation between monthly ice cream sales and the number of drowning deaths recorded in the same month, across many regions and years. This correlation has sometimes been used as a classic example in statistics classes. Some early, informal reports framed it as evidence that eating ice cream increases the risk of drowning.

B7. What’s being correlated here? Is this an observational study, an experiment, or something else (no individual people were surveyed — think about what kind of data this actually is)?

ANSWER: It correlates monthly ice cream sales with monthly drowning deaths. It’s observational, built from existing records rather than an experiment, and the data are aggregate monthly totals instead of surveys of individual people.

B8. Name the confounding variable that explains this correlation much better than a cause-and-effect relationship between ice cream and drowning.

ANSWER: Warm weather, or summer temperature. When it’s hot, people buy more ice cream and also swim more, which raises drownings. Temperature drives both.

B9. In one or two sentences, explain the difference between correlation and causation, using this example to illustrate it.

ANSWER: Correlation means two things move together; causation means one actually produces the change in the other. Ice cream sales and drownings rise together, but ice cream doesn’t cause drowning. Warm weather lifts both, so this is correlation, not causation.

B10. Unlike Scenario 1, this example doesn’t really involve a “sample of people.” What kind of data is being compared instead, and why does that make it harder (or different) to talk about sampling bias here?

ANSWER: The data are aggregate monthly totals for whole regions, not a sample of individual people. Because the units are months and places rather than sampled persons, the usual worry about who got picked matters less. The bigger concerns are confounding and how the time periods and regions were chosen.


Final Reflection

B11. Of everything we covered this week — data types, base R graphs, ggplot with filter/mutate/color, bias, sampling, and experimental design — which concept do you feel most confident about, and which one do you want more practice with? Be specific. When you are finished please knit and print or email me your final product.

ANSWER: I feel most confident with ggplot using filter, mutate, and color. I want more practice with confounding variables and study redesign.