Psych 251 PS4: Simulation + Analysis

Author

Linas Nasvytis (linasmn)

Published

December 31, 2024

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(readr)
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.

library(ggplot2)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
# keep one age per infant
fvs_unique <- fvs %>% distinct(subid, age)

# histogram of ages
ggplot(fvs_unique, aes(x = age)) +
  geom_histogram(binwidth = 1, color = "white") +
  labs(title = "Distribution of Infant Ages",
       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.6) +
  geom_smooth(method = "loess", se = FALSE) +
  labs(
    title = "Hand Looking as a Function of Age and Condition",
    x = "Age (months)",
    y = "Proportion Looking at Hands",
    color = "Condition"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(face = "bold"),
    legend.position = "right"
  )
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

First, the pattern of infants looking at hands is relatively low and stable from early infancy (3 months) to around 10–12 months, with little difference between the two conditions during this period. After about one year of age, the two conditions begin to diverge: children in the Faces_Plus condition appear to show higher hand-looking than those in the Faces_Medium condition, with the difference peaking roughly around 16–18 months of age. Later in development (starting 20 months), the Faces_Plus curve begins to bend downward, while the Faces_Medium curve shows a gradual increase, suggesting that the developmental trajectories may differ across conditions. Overall, the data is consistent with a potential age × condition interaction, where condition differences emerge only at later ages rather than uniformly across development.

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

I’d test how age and condition relate to hand-looking by fitting a regression model, first checking the main effects and then adding an age × condition interaction to see whether the developmental trend differs between the two conditions. Since each child contributes multiple observations, the appropriate version of this analysis is a mixed-effects model with a random intercept for each infant: lmer(hand.look ~ age * condition + (1 | subid), data = fvs). A significant interaction would show that the two conditions diverge as children get older.

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)

n_sims <- 10000
p_vals <- numeric(n_sims)

for (i in 1:n_sims) {
  x <- rnorm(30, mean = 0, sd = 1)
  
  t_res <- t.test(x, mu = 0)
  
  p_vals[i] <- t_res$p.value
}

mean(p_vals < 0.05)
[1] 0.0487

Next, do this using the replicate function:

set.seed(42)

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

mean(p_vals_rep < 0.05)
[1] 0.0487

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

The estimated false-positive rate from the simulations is around 0.0487, which is essentially the same as the intended α = 0.05. In other words, the t-test behaves as expected under the null: it produces significant results 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() {
  x1 <- rnorm(30, mean = 0, sd = 1)
  t1 <- t.test(x1, mu = 0)
  p1 <- t1$p.value
  
  if (p1 < 0.05 || p1 > 0.25) {
    return(p1)
  } else {
    x2 <- rnorm(30, mean = 0, sd = 1)
    x_all <- c(x1, x2)
    t2 <- t.test(x_all, mu = 0)
    return(t2$p.value)
  }
}

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

set.seed(42)

pvals_double <- replicate(10000, double.sample())

mean(pvals_double < 0.05)
[1] 0.0714

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

Yes — the false-positive rate increases from the intended 5% to about 7%. That’s a noticeable inflation: you’re getting roughly 40% more false positives than you should. Even this simple form of optional stopping makes “significant” results meaningfully more common under the null.

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.

set.seed(42)

double.sample <- function(upper_thresh = 0.25) {
  
  x1 <- rnorm(30, mean = 0, sd = 1)
  p1 <- t.test(x1, mu = 0)$p.value
  
  #if p < .05 --> stop (sig)
  #if p > upper_thresh --> stop (not close)
  #if .05 < p < upper_thresh --> double sample
  
  if (p1 < 0.05 || p1 > upper_thresh) {
    return(p1)
  } else {
    # collect more data
    x2 <- rnorm(30, mean = 0, sd = 1)
    p2 <- t.test(c(x1, x2), mu = 0)$p.value
    return(p2)
  }
}


#upper_thresh = 0.25 --> original
#upper_thresh = 0.50 --> "double if non-sig but p < .5"
#upper_thresh = 0.75 --> "double if non-sig but p < .75"
#upper_thresh = 1.00 --> "double for ANY non-sig p"
thresholds <- c(0.25, 0.50, 0.75, 1.00)

results <- tibble(
  threshold = thresholds,
  false_positive_rate = map_dbl(
    thresholds,
    ~ mean(replicate(10000, double.sample(upper_thresh = .x)) < 0.05)
  )
)

results
# A tibble: 4 × 2
  threshold false_positive_rate
      <dbl>               <dbl>
1      0.25              0.0714
2      0.5               0.0803
3      0.75              0.0822
4      1                 0.0799

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

These simulations show that even a simple, seemingly “reasonable” data-dependent rule can inflate the false-positive rate. With the original rule (only doubling when .05 < p < .25), the false-positive rate is already around 7% instead of the intended 5%. When the researcher gets more optimistic and is willing to double for larger p-values, the false-positive rate increases to up to around 8%. That’s roughly a 40–60% increase over the nominal α = .05. So this kind of policy actually makes “significant” results meaningfully more common under the null, which means reported p-values no longer reflect their advertised error rate. In other words, optional stopping like this quietly makes your science more false-positive-prone.