Psych 251 PS4: Simulation + Analysis

Author

Ramya Kumar

Published

November 22, 2025

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)
Warning: package 'tidyverse' was built under R version 4.4.2
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── 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.

theme_set(theme_classic())

fvs.1 <- fvs %>%
  group_by(subid) %>%
  slice(1) %>%
  ungroup()

fvs.p1 <- ggplot(fvs.1, aes(x = age)) +
  geom_histogram(binwidth = 1, fill = "blue", color = "black", alpha = 0.7) +
  labs(title = "Histogram of children's age",
       x = "Age (years)",
       y = "Frequency")

print(fvs.p1)

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.p2 <- ggplot(fvs, aes(x = age, y = hand.look, color = condition)) +
  geom_point(alpha = 0.4, size = 2.5) +
  geom_smooth(method = "lm", se = TRUE, linewidth = 1.2) +
  labs(title = "Hand-looking behavior by children's age and movie condition",
       caption = "Linear regression with standard error represented",
       x = "Age (years)",
       y = "Hand-looking duration",
       color = "Movie Condition") +
  scale_color_manual(values = c("green", "orange"),
                     labels = c("Face Medium", "Face Plus"))

print(fvs.p2)
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

At an older age, people are looking at their hand more. Across conditions, especially as children age they are more likely to look at their hand in the face plus condition than the face medium condition.

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

Linear regression with interaction of age and movie condition.

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(123)

n_significant <- 0
n_simulations <- 10000

for (i in 1:n_simulations) {
  sample_data <- rnorm(30, mean = 0, sd = 1)
  t_result <- t.test(sample_data, mu = 0)
  if (t_result$p.value < 0.05) {
    n_significant <- n_significant + 1
  }
}

false_positive_rate <- n_significant / n_simulations
print(false_positive_rate)
[1] 0.0465

Next, do this using the replicate function:

set.seed(123)


n_simulations <- 10000

p_values <- replicate(n_simulations, {
  sample_data <- rnorm(30, mean = 0, sd = 1)
  t_result <- t.test(sample_data, mu = 0)
  t_result$p.value
})


false_positive_rate_replicate <- mean(p_values < 0.05)
print(false_positive_rate_replicate)
[1] 0.0465

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

The value is very similar, which means the t-tests are producing the false positive rate that we specified (0.05). The small difference could be due to random variation in our simulation.

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() {
  sample1 <- rnorm(30, mean = 0, sd = 1)
  t_result1 <- t.test(sample1, mu = 0)
  p_value1 <- t_result1$p.value
  if (p_value1 >= 0.05 & p_value1 < 0.25) {
    sample2 <- rnorm(30, mean = 0, sd = 1)
    combined_sample <- c(sample1, sample2)
    t_result_final <- t.test(combined_sample, mu = 0)
    p_value_final <- t_result_final$p.value
    return(p_value_final)
  } else {
    return(p_value1)
  }
}

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

set.seed(123)

n_simulations <- 10000
p_values_double <- replicate(n_simulations, double.sample())

false_positive_rate_double <- mean(p_values_double < 0.05)
print(false_positive_rate_double)
[1] 0.0669

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

Yes, there is an inflation of the false positives, there is a 1.69% increase in likelyhood of recieving a 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.

double.sample <- function(p_max = 0.25) {
  sample1 <- rnorm(30, mean = 0, sd = 1)
  t_result1 <- t.test(sample1, mu = 0)
  p_value1 <- t_result1$p.value
  if (p_value1 >= 0.05 & p_value1 < p_max) {
    sample2 <- rnorm(30, mean = 0, sd = 1)
    combined_sample <- c(sample1, sample2)
    t_result_final <- t.test(combined_sample, mu = 0)
    p_value_final <- t_result_final$p.value
    return(p_value_final)
  } else {
    return(p_value1)
  }
}

set.seed(123)

n_simulations <- 20000

p_thresholds <- c(0.25, 0.5, 0.75, 1.0)

false_positive_rates <- numeric(length(p_thresholds))

for (i in seq_along(p_thresholds)) {
  p_values <- replicate(n_simulations, double.sample(p_max = p_thresholds[i]))
  false_positive_rates[i] <- mean(p_values < 0.05)
}


results_df <- data.frame(
  p_max = p_thresholds,
  FPR = false_positive_rates)

print(results_df)
  p_max     FPR
1  0.25 0.07045
2  0.50 0.07945
3  0.75 0.08105
4  1.00 0.08215

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

Looking at the simulations, it seems that doubling your sample size depending on your current p-values increases the likelyhood of getting a false positive. From our set alpha of 0.05, each of the scenraios had increases in false positives of 2-3%. This data-dependent policy of determining sample size seems quite bad, so it would be important to calculate the estimated sample size based on power calculations.