Psych 251 PS4: Simulation + Analysis

Author

Seojin Lee

Published

December 31, 2018

This is problem set #4, in which we want you to integrate your knowledge of data wrangling with some basic simulation skills. It’s a short problem set to help consolidate your ggplot2 skills and then help you get your feet wet in testing statistical concepts through “making up data” rather than consulting a textbook or doing math.

For ease of reading, please separate your answers from our text by marking our text with the > character (indicating quotes).

Part 1: ggplot practice

This part is a warmup, it should be relatively straightforward ggplot2 practice.

Load data from Frank, Vul, Saxe (2011, Infancy), a study in which we measured infants’ looking to hands in moving scenes. There were infants from 3 months all the way to about two years, and there were two movie conditions (Faces_Medium, in which kids played on a white background, and Faces_Plus, in which the backgrounds were more complex and the people in the videos were both kids and adults). An eye-tracker measured children’s attention to faces. This version of the dataset only gives two conditions and only shows the amount of looking at hands (other variables were measured as well).

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.1     ✔ stringr   1.5.2
✔ ggplot2   4.0.0     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.0     
── 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
fvs <- read_csv("data/FVS2011-hands.csv")
Rows: 232 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): condition
dbl (3): subid, age, hand.look

ℹ 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.

First, use ggplot to plot a histogram of the ages of children in the study. NOTE: this is a repeated measures design, so you can’t just take a histogram of every measurement.

# dataset has repeated measures, use one row per kid
fvs_unique <- fvs |> distinct(subid, .keep_all = TRUE)

ggplot(fvs_unique, aes(x = age)) +
  geom_histogram(binwidth = 1) +
  labs(x = "Age (months)", y = "Count")

Second, make a scatter plot showing hand looking as a function of age and condition. Add appropriate smoothing lines. Take the time to fix the axis labels and make the plot look nice.

ggplot(fvs, aes(x = age, y = hand.look, color = condition)) +
  geom_point(alpha = 0.5) +
  geom_smooth() +
  labs(
    x = "Age (months)",
    y = "Looking to hands",
    color = "Condition"
  ) +
  theme_minimal()
`geom_smooth()` using method = 'loess' and formula = 'y ~ x'

What do you conclude from this pattern of data?

Looking at the scatterplot, it seems like hand-looking changes with age in a curved, non-linear way. Very young infants tend to look at hands less, then hand-looking gradually increases through the middle of the age range (around 15–20 months). After about 20 months, the two conditions start to separate: in the Faces_Plus condition hand-looking drops off again, while in the Faces_Medium condition it keeps rising slightly. Overall, hand-looking clearly isn’t constant across age, and the two conditions show somewhat different developmental patterns.

What statistical analyses would you perform here to quantify these differences?

To quantify this, I would run a model that includes both age and condition as predictors—probably a linear model with an age × condition interaction. Because the pattern looks non-linear, I would either add a quadratic age term or use a GAM (generalized additive model) to capture the smooth changes over age. I would then test whether the interaction is significant, i.e., whether the two conditions differ in how hand-looking changes with age.

Part 2: Simulation

library(tidyverse)

Let’s start by convincing ourselves that t-tests have the appropriate false positive rate. Run 10,000 t-tests with standard, normally-distributed data from a made up 30-person, single-measurement experiment (the command for sampling from a normal distribution is rnorm).

The goal of these t-tests are to determine, based on 30 observations, whether the underlying distribution (in this case a normal distribution with mean 0 and standard deviation 1) has a mean that is different from 0. In reality, the mean is not different from 0 (we sampled it using rnorm), but sometimes the 30 observations we get in our experiment will suggest that the mean is higher or lower. In this case, we’ll get a “significant” result and incorrectly reject the null hypothesis of mean 0.

What’s the proportion of “significant” results (\(p < .05\)) that you see?

First do this using a for loop.

set.seed(42)

nsim <- 10000
pvals <- numeric(nsim)

for (i in 1:nsim) {
  x <- rnorm(30, mean = 0, sd = 1)   # generate data under the null
  test <- t.test(x, mu = 0)
  pvals[i] <- test$p.value
}

mean(pvals < 0.05)
[1] 0.0487

Next, do this using the replicate function:

set.seed(42)

pvals_rep <- replicate(
  10000,
  t.test(rnorm(30, mean = 0, sd = 1), mu = 0)$p.value
)

mean(pvals_rep < 0.05)
[1] 0.0487

How does this compare to the intended false-positive rate of \(\alpha=0.05\)?

Both the for-loop and the replicate() simulation produced a false-positive rate of about 0.0487, which is basically the same as the theoretical value of α = 0.05. In other words, the t-test behaves as expected under the null. It gives a significant result about 5% of the time just by chance.

Ok, that was a bit boring. Let’s try something more interesting - let’s implement a p-value sniffing simulation, in the style of Simons, Nelson, & Simonsohn (2011).

Consider this scenario: you have done an experiment, again with 30 participants (one observation each, just for simplicity). The question is whether the true mean is different from 0. You aren’t going to check the p-value every trial, but let’s say you run 30 - then if the p-value is within the range p < .25 and p > .05, you optionally run 30 more and add those data, then test again. But if the original p value is < .05, you call it a day, and if the original is > .25, you also stop.

First, write a function that implements this sampling regime.

double.sample <- function() {
  # Step 1: collect first 30 samples
  x1 <- rnorm(30, mean = 0, sd = 1)
  p1 <- t.test(x1, mu = 0)$p.value
  
  #  if p1 < .05: stop (significant)
  #  if p1 > .25: stop (not significant)
  #  else (between .05 and .25): collect 30 more samples
  
  if (p1 < 0.05) {
    return(1)   # false positive detected
  } else if (p1 > 0.25) {
    return(0)   #  not significant
  } else {
    # collect 30 more samples
    x2 <- rnorm(30, mean = 0, sd = 1)
    x_full <- c(x1, x2)
    p2 <- t.test(x_full, mu = 0)$p.value
    return(as.numeric(p2 < 0.05))
  }
}

Now call this function 10k times and find out what happens.

set.seed(42)

results <- replicate(10000, double.sample())
mean(results)
[1] 0.0714

Is there an inflation of false positives? How bad is it?

The false-positive rate jumped from about 0.05 to around 0.07 in my simulation. So optional sampling (only adding subjects when the initial p-value is “almost significant”) inflates Type I error pretty noticeably. Even this mild p-hacking nearly doubles the false-positive rate compared to the nominal α = .05.

Now modify this code so that you can investigate this “double the sample” rule in a bit more depth. In the previous question, the researcher doubles the sample only when they think they got “close” to a significant result, i.e. when their not-significant p is less than 0.25. What if the researcher was more optimistic? See what happens in these 3 other scenarios:

  • The researcher doubles the sample whenever their pvalue is not significant, but it’s less than 0.5.
  • The researcher doubles the sample whenever their pvalue is not significant, but it’s less than 0.75.
  • The research doubles their sample whenever they get ANY pvalue that is not significant.

How do these choices affect the false positive rate?

HINT: Try to do this by making the function double.sample take the upper p value as an argument, so that you can pass this through dplyr.

HINT 2: You may need more samples. Find out by looking at how the results change from run to run.

double.sample <- function(upper = 0.25) {
  x1 <- rnorm(30, mean = 0, sd = 1)
  p1 <- t.test(x1, mu = 0)$p.value
  
  # stop if significant
  if (p1 < 0.05) {
    return(1)
  }
  
  # stop if not significant AND above the cutoff
  if (p1 > upper) {
    return(0)
  }
  
  # otherwise: p is "close enough" → collect 30 more
  x2 <- rnorm(30, mean = 0, sd = 1)
  x_full <- c(x1, x2)
  p2 <- t.test(x_full, mu = 0)$p.value
  
  return(as.numeric(p2 < 0.05))
}

# Run for multiple different thresholds
set.seed(42)
res_25 <- replicate(20000, double.sample(upper = 0.25))
mean(res_25)
[1] 0.0728
set.seed(42)
res_50 <- replicate(20000, double.sample(upper = 0.50))
mean(res_50)
[1] 0.07865
set.seed(42)
res_75 <- replicate(20000, double.sample(upper = 0.75))
mean(res_75)
[1] 0.08315
set.seed(42)
res_100 <- replicate(20000, double.sample(upper = 1.00))
mean(res_100)
[1] 0.08245

What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?

When I made the optional-sampling rule more permissive, the false-positive rate kept increasing. With the original rule (double sample if .05 < p < .25), the false-positive rate was already above 0.07. When I increased the cutoff to 0.50 or 0.75, the false-positive rate rose even more (around 0.08). When I doubled the sample every time the first test wasn’t significant, the rate stayed high (around 0.082). Overall, this shows that data-dependent sample increases inflate false positives noticeably above the intended 0.05, even when the rule seems mild.