Psych 251 PS4: Simulation and Analysis

Author

Emily Chen

Published

November 26, 2023

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 warm-up, 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")

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.

suppressMessages(library(dplyr))
suppressMessages(library(ggplot2))

#Get just one row per subject 
subjects <- fvs |> 
  group_by(subid) |> 
  summarize(mean_age = mean(age)) #Ages are the same at both time points

# Create a histogram of ages
histogram_plot <- ggplot(subjects, aes(x = mean_age)) +
  geom_histogram() +
  labs(title = "Histogram of Children's Ages",
       x = "Age (in months)",
       y = "Frequency")

# Display the histogram plot
print(histogram_plot)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

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.

# Create the scatter plot
scatter_plot <- ggplot(fvs, aes(x = age, y = hand.look, color = condition)) +
  geom_point() +               
  geom_smooth(method = "lm", #Add linear regression lines
              se = TRUE) + #Show confidence intervals
  labs(title = "Scatter Plot of Hand-Looking vs. Age by Condition",
       x = "Age",
       y = "Hand-Looking") +
  theme_minimal() 

# Display the scatter plot
print(scatter_plot)
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

As children get older, they tend to look more towards hands overall, and also look more at hands in the condition with videos containing more complex backgrounds and both children and adult characters.

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

I would test for the effect of age on proportion of looking towards hands in both the Faces_Medium and Faces_Plus conditions, as well as the interaction effect between the two conditions.

Part 2: Simulation

library(tidyr)

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 a seed to get the same proportion each time 
set.seed(123) 

#Define the number of t-tests 
num_tests <- 10000

#Define the number of subjects per test (observations)
n <- 30

#Initialize a count for significant results
significant_count <- 0

#Run 10,000 t-tests and count significant results
for (i in 1:num_tests) {
  #Generate data for Treatment and Control groups
  data <- rnorm(n, mean = 0, sd = 1)  # True mean is 0, Standard Deviation = 1
  
  #Perform t-test
  t_test_result <- t.test(data)
  
  # Check if the p-value is less than 0.05
  if (t_test_result$p.value < 0.05) {
    significant_count <- significant_count + 1
  }
}

#Calculate the proportion of significant results
proportion_significant <- significant_count / num_tests

cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.0465 

Next, do this using the replicate function:

#Redefine the variables 
set.seed(123) 
num_tests <- 10000
n <- 30

#Create a function to perform a single t-test that returns if the t-test is significant
perform_t_test <- function() {
  data <- rnorm(n, mean = 0, sd = 1)
  t_test_result <- t.test(data)
  return(t_test_result$p.value < 0.05) #TRUE or FALSE
}

#Use replicate to run 10,000 t-tests and calculate the proportion of significant results
results_simulation <- replicate(num_tests, perform_t_test())
proportion_significant <- mean(results_simulation)

cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.0465 

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

Even though I set a seed to generate the same answer each time, I also removed the seed to get different proportion values each time. In this case, the proportion of significant results \((0.0465)\) indicates that there were fewer significant results (without rounding) than the false-positive rate of \(\alpha=0.05\) but that it’s very close.

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() {
  #Generate random data for the experiment with 30 participants 
  data <- rnorm(30)  
  
  #Perform a t-test to check if the true mean is different from 0
  t_test_result <- t.test(data, mu = 0)
  p_value <- t_test_result$p.value
  
  #Check if the p-value is within the range p > .05 and p < .25 
  if (p_value > 0.05 && p_value < 0.25) {
    #If so, run 30 more participants and add those data to the old data 
    additional_data <- rnorm(30)
    data <- c(data, additional_data)
  } 
  
  #Perform the final t-test on the accumulated data
  t_test_result_final <- t.test(data, mu = 0)
  p_value_final <- t_test_result_final$p.value
  
  return(p_value_final < 0.05) #TRUE or FALSE
}

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

#Use replicate to run 10,000 t-tests and calculate the proportion of significant results
num_tests <- 10000
results_p_sniffing <- replicate(num_tests, double.sample())
proportion_significant <- mean(results_p_sniffing)

cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.073 

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

There is an inflation of about 0.02 (or 2%) relative to the false-positive rate of \(\alpha=0.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 p-value is not significant, but it’s less than 0.5.
  • The researcher doubles the sample whenever their p-value is not significant, but it’s less than 0.75.
  • The research doubles their sample whenever they get ANY p-value 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.

double.sample.updated <- function(p_value_threshold) {
  #Generate random data for the experiment with 30 participants 
  n <- 30
  data <- rnorm(n)  
  
  #Perform a t-test to check if the true mean is different from 0
  t_test_result <- t.test(data, mu = 0)
  p_value <- t_test_result$p.value
  
  #Check if the p-value is within the range p > .05 and p < .25 
  if (p_value > 0.05 && p_value < p_value_threshold) {
    #If so, double the number of participants and add those data to the old data 
    additional_data <- rnorm(n)
    data <- c(data, additional_data)
  } 
  
  #Perform the final t-test on the accumulated data
  t_test_result_final <- t.test(data, mu = 0)
  p_value_final <- t_test_result_final$p.value
  
  return(p_value_final < 0.05) #TRUE or FALSE
}

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

#Use replicate to run 10,000 t-tests and calculate the proportion of significant results
num_tests <- 10000

#Scenario 1: upper p-value = 0.5
p_value_threshold <- 0.5
results_doubling <- replicate(num_tests, double.sample.updated(p_value_threshold))
proportion_significant <- mean(results_doubling)
cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.0812 
#Scenario 2: upper p-value = 0.75
p_value_threshold <- 0.75
results_doubling <- replicate(num_tests, double.sample.updated(p_value_threshold))
proportion_significant <- mean(results_doubling)
cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.0822 
#Scenario 3: upper p-value = 1 (any non-significant results)
p_value_threshold <- 1
results_doubling <- replicate(num_tests, double.sample.updated(p_value_threshold))
proportion_significant <- mean(results_doubling)
cat("Proportion of significant results (p < 0.05):", proportion_significant, "\n")
Proportion of significant results (p < 0.05): 0.0819 

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

The higher the p-value threshold is, the greater the number of significant results (or false-positives). In other words, by increasing the sample size based on an increasingly larger range of non-significant p-values, there is a greater likelihood of obtaining a false positive result.