Psych 251 PS4: Simulation + Analysis

Author

Karla Perez

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

# import packages
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
library(readr)

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

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.

fvs %>% 
  distinct(subid, .keep_all = TRUE) %>% 
  ggplot(aes(age)) + geom_histogram(bins = 40) +
  theme_classic()

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.

fvs %>% 
  ggplot(aes(age, hand.look, color = condition)) + 
  geom_point() +
  geom_smooth(method = "lm") +
  theme_classic() +
  labs(title = "Hand Looking Time as a Function of Age and Condition",
    x = "Age (months)",
    y = "Hand Looking Time (seconds)",
    color = "Condition")
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

As children get older, they look longer at hands. This is especially true in the Faces_Plus condition.

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

I would run a linear regression.

Part 2: Simulation

library(tidyverse)
library(purrr)

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.

count <- 0

for (i in 1:10000) {
  fake_data <- rnorm(30, 0, 1)
  t_test <- t.test(fake_data, mu = 0)
  p_value <- t_test$p.value
  if (p_value < 0.05) {
    count <- count + 1
  }
}

print(count/10000) # proportion of "significant" results (p < .05)
[1] 0.0456

Next, do this using the replicate function:

mean(replicate(10000, {t.test(rnorm(30, mean = 0, sd = 1), mu = 0)$p.value}) < .05)
[1] 0.0506

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

This is very close to the intended false-positive rate of \(\alpha=0.05\)?

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() {
  data <- numeric()
  continue_sampling <- TRUE
  
  while (continue_sampling) {
    new_data <- rnorm(30, mean = 0, sd = 1)
    data <- c(data, new_data)
    
    p_val <- t.test(data, mu = 0)$p.value
    
    if (p_val < 0.05) {
      continue_sampling <- FALSE
    } else if (p_val > 0.25) {
      continue_sampling <- FALSE
    } else {
    }
  }
  
  return(p_val)
}

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

sim_results <- replicate(10000, double.sample())
sum_p <- sum(sim_results < 0.05) / 10000
sum_p
[1] 0.0885

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

Yes, but not thaaaat bad. That being said, I have no real priors on inflation of false positives.

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.

optional.stopping.sample <- function(p_upper, N_max = 5000) { # limit bc will run for forever otherwise
 data <- numeric()
 repeat {
 new_data <- rnorm(30, mean = 0, sd = 1)
 data <- c(data, new_data)
 
 if (length(data) > N_max) {
   break
   }
 
 p_val <- t.test(data, mu = 0)$p.value

 if (p_val < 0.05) {
   break 
   }
 else if (p_val >= p_upper) {
   break
   }
 else {

 }
 } 
 return(p_val)
}
N_SIMS <- 1000

p_thresholds <- c(
  'p_upper_0.25' = 0.25,
  'p_upper_0.50' = 0.50,
  'p_upper_0.75' = 0.75,
  'p_upper_1.00' = 1.00
)

simulation_results <- purrr::map_dfr(p_thresholds, ~ {
  p_values <- replicate(N_SIMS, optional.stopping.sample(p_upper = .x))
  print(paste("case where p_upper =", .x, "is done")) 
  fpr <- mean(p_values < 0.05)
  tibble::tibble(
    p_upper = .x,
    false_positive_rate = fpr
  )
}, .id = "scenario")
[1] "case where p_upper = 0.25 is done"
[1] "case where p_upper = 0.5 is done"
[1] "case where p_upper = 0.75 is done"
[1] "case where p_upper = 1 is done"
baseline_fpr <- mean(replicate(N_SIMS, {t.test(rnorm(30, mean = 0, sd = 1), mu = 0)$p.value}) < .05)
baseline_row <- tibble::tibble(scenario = "No Stopping Rule (Baseline)", 
                       p_upper = NA, false_positive_rate = baseline_fpr)

final_results <- bind_rows(baseline_row, simulation_results) %>%
  dplyr::mutate(scenario_desc = case_when(
    scenario == "No Stopping Rule (Baseline)" ~ "baseline (no doubling)",
    scenario == "p_upper_0.25" ~ "double if p < 0.25",
    scenario == "p_upper_0.50" ~ "double if p < 0.50",
    scenario == "p_upper_0.75" ~ "double if p < 0.75",
    scenario == "p_upper_1.00" ~ "any non-sig: double if p < 1.00"
  )) %>%
  dplyr::select(scenario_desc, p_upper, false_positive_rate)

print(final_results)
# A tibble: 5 × 3
  scenario_desc                   p_upper false_positive_rate
  <chr>                             <dbl>               <dbl>
1 baseline (no doubling)            NA                  0.049
2 double if p < 0.25                 0.25               0.097
3 double if p < 0.50                 0.5                0.133
4 double if p < 0.75                 0.75               0.193
5 any non-sig: double if p < 1.00    1                  0.397

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

This is really bad! And even scarier because we know that the null hypothesis is true in this case, and yet the more I sampled, the more I increased my chances of a false positive. Thanks–cool visual for why pre-registration is important!