Psych 251 PS4: Simulation + Analysis

Author

Mike Frank

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

setwd("/Users/willblakey/problem_sets/data")

fvs <- read.csv("FVS2011-hands.csv")

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
✓ ggplot2 3.3.6     ✓ purrr   0.3.4
✓ tibble  3.1.6     ✓ dplyr   1.0.8
✓ tidyr   1.1.3     ✓ stringr 1.4.0
✓ readr   1.4.0     ✓ forcats 0.5.1
Warning: package 'dplyr' was built under R version 4.0.5
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
x dplyr::filter() masks stats::filter()
x dplyr::lag()    masks stats::lag()
library(ggplot2)

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.

ggplot(fvs, aes(x = age)) +
  geom_histogram(binwidth = 1, fill = "skyblue", color = "black", alpha = 0.7) +
  labs(title = "Histogram of Children's Ages",
       x = "Age",
       y = "Number of Children") +
  theme_minimal()

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.7) +
  geom_smooth(method = "lm", se = T) + # Add linear regression line
  labs(title = "Scatter Plot of Hand Looking by Age and Condition",
       x = "Age",
       y = "Hand Looking",
       color = "Condition") +
  theme_minimal()
`geom_smooth()` using formula 'y ~ x'

What do you conclude from this pattern of data?

As people age, they are better able to focus on the hand (and by proxy the character) and ignore background features.

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

To examine the unique contribution of age and condition while controlling for each other, I’d use multiple linear regression.

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.

# Simulate 10,000 t-tests using a for loop
num_simulations <- 10000
sample_size <- 30

# Initialize a vector to store results
results <- numeric(num_simulations)

# Loop through simulations
for (i in 1:num_simulations) {
  # Generate a sample from a normal distribution with mean 0
  data <- rnorm(sample_size, mean = 0)
  
  # Conduct t-test
  t_test_result <- t.test(data)
  
  # Store whether the result is significant at alpha = 0.05
  results[i] <- t_test_result$p.value < 0.05
}

# Calculate the proportion of "significant" results
proportion_significant <- mean(results)

# Display the result
cat("Proportion of 'significant' results:", proportion_significant, "\n")
Proportion of 'significant' results: 0.0512 

Next, do this using the replicate function:

# Simulate 10,000 t-tests using replicate
num_simulations <- 10000
sample_size <- 30

# Use replicate to run the simulation and store results
results <- replicate(num_simulations, {
  # Generate a sample from a normal distribution with mean 0
  data <- rnorm(sample_size, mean = 0)
  
  # Conduct t-test
  t_test_result <- t.test(data)
  
  # Return whether the result is significant at alpha = 0.05
  t_test_result$p.value < 0.05
})

# Calculate the proportion of "significant" results
proportion_significant <- mean(results)

# Display the result
cat("Proportion of 'significant' results:", proportion_significant, "\n")
Proportion of 'significant' results: 0.0476 

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

Pretty close - .0496 can round up to .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() {
  set.seed(123)  # Set seed for reproducibility
  
  num_participants <- 30
  alpha_upper <- 0.25
  alpha_lower <- 0.05
  max_iterations <- 3  # Maximum number of iterations
  
  iterations <- 0
  p_value <- NULL
  
  repeat {
    # Generate a sample from a normal distribution with mean 0
    data <- rnorm(num_participants, mean = 0)
    
    # Conduct t-test
    t_test_result <- t.test(data)
    
    # Check the p-value
    p_value <- t_test_result$p.value
    
    # Check stopping conditions
    if (p_value > .25 || p_value < .05 || iterations == max_iterations) {
      break
    }
    
    # If the p-value is within the range (0.05 < p < 0.25), run 30 more participants
    num_participants <- num_participants + 30
    iterations <- iterations + 1
  }
  
  # Return the final p-value and the number of participants
  return(list(p_value = p_value, num_participants = num_participants))
}

# Example usage
result <- double.sample()
cat("Final p-value:", result$p_value, "\n")
Final p-value: 0.7944204 
cat("Number of participants:", result$num_participants, "\n")
Number of participants: 30 

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

# Function to perform the double sampling
double.sample <- function() {
  # Initial sample
  sample1 <- rnorm(30)
  p_value1 <- t.test(sample1)$p.value
  
  # Check stopping criteria
  if (0.05 < p_value1 & p_value1 < 0.25) {
    # If within the range, collect additional data
    sample2 <- c(sample1, rnorm(30))
    p_value2 <- t.test(sample2)$p.value
    
    return(p_value2)
  } else {
    # Otherwise, return the initial p-value
    return(p_value1)
  }
}

# Perform the double sampling 10,000 times
results <- replicate(10000, double.sample())

# Count the proportion of false positives
false_positives <- mean(results < 0.05)

# Print the proportion of false positives
cat("Proportion of False Positives:", false_positives, "\n")
Proportion of False Positives: 0.0669 

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

Yes, but it doesnt seem so bad? I assume i did something wrong here - only a .02 increase.

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.

# Function to perform the double sampling with different upper p-value thresholds
double.sample <- function(upper_threshold) {
  # Initial sample
  sample1 <- rnorm(30)
  p_value1 <- t.test(sample1)$p.value
  
  # Check stopping criteria
  if (!t.test(sample1)$p.value < 0.05) {
    # If not significant, double the sample based on the upper threshold
    if (p_value1 < upper_threshold) {
      sample2 <- c(sample1, rnorm(30))
      p_value2 <- t.test(sample2)$p.value
      return(p_value2)
    }
  }
  
  # Otherwise, return the initial p-value
  return(p_value1)
}

# Number of simulations
num_simulations <- 10000

# Perform the double sampling with different upper thresholds
thresholds <- c(0.5, 0.75, 1.0)  # Upper p-value thresholds to explore

# Store results for each threshold
results_list <- lapply(thresholds, function(threshold) {
  replicate(num_simulations, double.sample(threshold))
})

# Calculate the proportion of false positives for each threshold
false_positives <- sapply(results_list, function(results) mean(results < 0.05))

# Print the results
cat("Proportion of False Positives (Upper Threshold 0.5):", false_positives[1], "\n")
Proportion of False Positives (Upper Threshold 0.5): 0.0817 
cat("Proportion of False Positives (Upper Threshold 0.75):", false_positives[2], "\n")
Proportion of False Positives (Upper Threshold 0.75): 0.0836 
cat("Proportion of False Positives (Upper Threshold 1.0):", false_positives[3], "\n")
Proportion of False Positives (Upper Threshold 1.0): 0.079 

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

I think i’m messing something up because my proportion of false positives are not inflating. I need help understanding what i did wrong here…