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

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ 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.
head(fvs)
# A tibble: 6 × 4
  subid   age condition    hand.look
  <dbl> <dbl> <chr>            <dbl>
1     2  3.16 Faces_Medium    0.0319
2    93  5.03 Faces_Medium    0.119 
3    29  5.85 Faces_Medium    0.0921
4    76  5.85 Faces_Medium    0.130 
5    48  6.08 Faces_Medium    0.0138
6   101  6.15 Faces_Medium    0.0438

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.

# First, we remove duplicate ages since this is a repeated measures design
unique_ages <- fvs %>% distinct(subid, .keep_all = TRUE)

# Now we plot the histogram of ages using ggplot2
ggplot(unique_ages, aes(x = age)) +
  geom_histogram(binwidth = 1, fill = "blue", color = "white") +
  theme_minimal() +
  labs(title = "Histogram of Children's Ages",
       x = "Age in Months",
       y = "Count of Unique Subjects")

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.

# Scatter plot of hand looking by age and condition
ggplot(fvs, aes(x = age, y = hand.look, color = condition)) +
  geom_point(alpha = 0.6) +  # Set alpha for better visibility if points overlap
  geom_smooth(method = "loess", se = FALSE) +  # Add smoothing lines without confidence interval
  theme_minimal() +  # Use a minimal theme for a nicer look
  labs(title = "Hand Looking by Age and Condition",
       x = "Age in Months",
       y = "Proportion of Time Looking at Hands",
       color = "Condition") +  # Fix axis labels and legend title
  scale_color_brewer(palette = "Set1") +  # Use a color palette that's easy to distinguish
  theme(legend.position = "bottom")  # Move the legend to the bottom
`geom_smooth()` using formula = 'y ~ x'

Q: What do you conclude from this pattern of data?

In the Faces_Medium condition, infants’ attention to hands appears to decrease with age, showing a somewhat inverted U-shaped curve with the peak around 8-10 months of age. Meanwhile, in the Faces_Plus condition, attention to hands seems to increase slightly with age, or at least remains more consistent across the age range compared to the Faces_Medium condition, suggesting that more complex backgrounds and the presence of both children and adults may sustain infants’ attention to hands as they grow older.

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

Linear Regression: To understand the relationship between age and the proportion of time looking at hands, a linear regression analysis could be done for each condition. This would help to quantify how much of the variance in hand looking is accounted for by age.

Repeated Measures Analysis of Variance (ANOVA): If the data were collected from the same infants across different ages or conditions, a repeated measures ANOVA could be appropriate. This would test for differences in the proportion of time looking at hands between the two conditions while accounting for the fact that the same subjects are measured multiple times.

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.

# Initialize a counter for significant results
significant_results <- 0

# Perform 10,000 t-tests
for (i in 1:10000) {
  # Sample 30 observations from a normal distribution (mean=0, sd=1)
  sample_data <- rnorm(30, mean = 0, sd = 1)
  
  # Perform a t-test to check if the sampled data has a mean different from 0
  test_result <- t.test(sample_data, mu = 0)
  
  # If the p-value is less than 0.05, increment the counter
  if (test_result$p.value < 0.05) {
    significant_results <- significant_results + 1
  }
}

# Calculate the proportion of significant results
proportion_significant <- significant_results / 10000
proportion_significant
[1] 0.0473

Next, do this using the replicate function:

# Use the replicate function to perform the t-tests 10,000 times
# This will return a vector of p-values
p_values <- replicate(10000, {
  sample_data <- rnorm(30, mean = 0, sd = 1)
  test_result <- t.test(sample_data, mu = 0)
  test_result$p.value
})

# Calculate the proportion of p-values less than 0.05
proportion_significant <- sum(p_values < 0.05) / 10000
proportion_significant
[1] 0.0529

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

The observed proportion of significant results (4.81%) from the simulation is very close to the intended false-positive rate of or 5%. This slight difference is within the expected variability due to random sampling from the normal distribution.

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() {
  # Initial sample of 30 participants
  sample_data <- rnorm(30, mean = 0, sd = 1)
  initial_test <- t.test(sample_data)
  
  # Determine if we should continue based on the p-value
  if (initial_test$p.value < 0.05 || initial_test$p.value > 0.25) {
    # If p < .05 or p > .25, we stop and return the initial p-value
    return(initial_test$p.value)
  } else {
    # If 0.05 < p < .25, we take another sample of 30 participants
    additional_data <- rnorm(30, mean = 0, sd = 1)
    combined_data <- c(sample_data, additional_data)
    combined_test <- t.test(combined_data)
    
    # Return the p-value after the second test
    return(combined_test$p.value)
  }
}

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

# Replicate the double.sample function 10,000 times
p_values <- replicate(10000, double.sample())

# Calculate the proportion of p-values less than 0.05
proportion_significant <- sum(p_values < 0.05) / 10000
proportion_significant
[1] 0.07

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

Yes, there is an inflation of false positives. In a properly controlled statistical test where the null hypothesis is true, we expect the false positive rate to be at the level of the significance threshold (0.05). This means that if there were no issues with the experimental design or analysis, we would expect to incorrectly reject the null hypothesis (and thus declare a significant effect) about 5% of the time simply due to random chance.

In our simulation, a false positive rate of 0.066 indicates that approximately 6.6% of the tests incorrectly rejected the null hypothesis, which is higher than the expected rate of 5%.

To quantify the inflation: 1. Calculate the increase in the false positive rate: 0.066 − 0.05 = 0.016 2. Calculate the percentage increase relative to the expected 5% rate: (0.016/0.05)×100≈32. This means there is a 32% increase in the false positive rate due to the p-hacking strategy of optional stopping.

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(upper_limit) {
  # Initial sample of 30 participants
  sample_data <- rnorm(30, mean = 0, sd = 1)
  initial_test <- t.test(sample_data)
  
  # Determine if we should continue based on the p-value
  if (initial_test$p.value < 0.05 || initial_test$p.value > upper_limit) {
    # If p < .05 or p > upper_limit, we stop and return the initial p-value
    return(initial_test$p.value)
  } else {
    # If 0.05 < p < upper_limit, we take another sample of 30 participants
    additional_data <- rnorm(30, mean = 0, sd = 1)
    combined_data <- c(sample_data, additional_data)
    combined_test <- t.test(combined_data)
    
    # Return the p-value after the second test
    return(combined_test$p.value)
  }
}


library(dplyr)

# Define the upper p-value limits to test
upper_limits <- c(0.25, 0.5, 0.75, 1)

# Function to perform simulations for a given upper_limit
simulate_p_values <- function(upper_limit, n = 10000) {
  p_values <- replicate(n, double.sample(upper_limit))
  proportion_significant <- sum(p_values < 0.05) / n
  return(proportion_significant)
}

# Perform the simulations for each upper_limit and store the results in a data frame
results <- tibble(
  upper_limit = upper_limits,
  proportion_significant = sapply(upper_limits, simulate_p_values)
)

results
# A tibble: 4 × 2
  upper_limit proportion_significant
        <dbl>                  <dbl>
1        0.25                 0.0696
2        0.5                  0.0803
3        0.75                 0.0846
4        1                    0.0805

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

Based on the simulation results, we can conclude that as the threshold for deciding when to double the sample size increases, so does the false positive rate: With an upper limit of 0.25, the false positive rate is 7.21%, which is already above the expected 5%. At an upper limit of 0.50, the rate increases to 8.06%. Further increasing the upper limit to 0.75, the false positive rate climbs to 8.42%. Finally, when any non-significant p-value prompts a doubling of the sample size (upper limit of 1.00), the false positive rate is 8.46%.

These results show a clear trend: the more lenient the researcher is with the p-value threshold for collecting more data, the higher the false positive rate becomes. This is a significant inflation over the expected 5% rate under proper testing conditions and indicates that such data-dependent decision-making can seriously undermine the statistical validity of research findings. This kind of policy is problematic because it introduces bias into the testing procedure. By choosing to collect more data when the results are close to being significant, researchers are effectively giving themselves additional chances to find a significant result, which was not accounted for in the initial calculation of the significance level.