Psych 251 PS4: Simulation + Analysis

Author

Sarah Tung 2023

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

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.

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ purrr     1.0.2
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.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
unique_ages <- fvs %>% distinct(subid, age)

ggplot(unique_ages, aes(x = age)) +
  geom_histogram(binwidth = 1, fill = "#76b947", color = "black") +
  scale_x_continuous(breaks = seq(0, 30, by = 5), limits = c(0, 30)) + 
  theme_light() +
  labs(title = "Distribution of Children's Ages",
       x = "Age (Months)",  
       y = "Number of Children") +
  theme(plot.title = element_text(hjust = 0.5),
        legend.position = "bottom",
    panel.grid.major = element_blank(),  
    panel.grid.minor = element_blank(),  
    panel.background = element_blank(),  
    axis.line = element_line(color = "black"),  
    axis.ticks = element_line(color = "black") 
  )
Warning: Removed 2 rows containing missing values (`geom_bar()`).

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() +
  geom_smooth(method = "lm", se = FALSE) +  # was not sure what smoothing to do so I did lm instead, looking at the plots from mike's paper
  scale_color_manual(values = c("Faces_Medium" = "blue", "Faces_Plus" = "red")) +  
  theme_minimal() +
  labs(
    title = "Hand Looking",
    x = "Age (Months)",
    y = "Duration of Hand Looking (Seconds)",
    color = "Condition"
  ) +
  theme(
    plot.title = element_text(hjust = 0.5),
    legend.position = "bottom",
    panel.grid.major = element_blank(),  
    panel.grid.minor = element_blank(),  
    panel.background = element_blank(),  
    axis.line = element_line(color = "black"),  
    axis.ticks = element_line(color = "black")  
  )
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

The duration of hand looking increases with age for both conditions, but the slope seems to be steeper for the “Faces_Plus” condition, which could imply a more pronounced increase in hand looking duration with age in this condition compared to “Faces_Medium”. There is also variability in hand looking duration within each age group, which is expected in behavioral data. The spread of data points suggests individual differences among participants.

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

I would probably to do some sort of mixed-effects model, which would help understand the effect of age and condition on hand looking, accounting for the repeated measures per child.

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)  # For reproducibility
n_simulations <- 10000
n <- 30  # Sample size
significant_results <- 0

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

proportion_significant <- significant_results / n_simulations
proportion_significant
[1] 0.0465

Next, do this using the replicate function:

set.seed(123)  # For reproducibility
proportion_significant_replicate <- mean(
  replicate(
    n_simulations,
    t.test(rnorm(n, mean = 0, sd = 1))$p.value < 0.05
  )
)
proportion_significant_replicate
[1] 0.0465

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

It’s slightly below the intended false-positive rate of \(\alpha=0.05\), but within the expected variability due to random chance when conducting a large number of tests, so it seems like the the t-test is a reliable method for detecting a true null effect with an appropriately controlled false-positive rate.

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() {
  n <- 30
  data1 <- rnorm(n, mean = 0, sd = 1)
  test1 <- t.test(data1)

  if (test1$p.value < 0.05 || test1$p.value > 0.25) {
    return(test1$p.value)
  } else {
    data2 <- rnorm(n, mean = 0, sd = 1)
    test2 <- t.test(c(data1, data2))
    return(test2$p.value)
  }
}

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

set.seed(123) 
n_simulations <- 10000
significant_results <- sum(replicate(n_simulations, double.sample() < 0.05))
proportion_significant <- significant_results / n_simulations
proportion_significant
[1] 0.0669

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

There is an inflation of false positives. There is an increase in the Type I error rate, which can affect the reliability of statistical inferences, leading to more false claims of effect where none exists.

ANSWER

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_upper_threshold) {
  n <- 30
  data1 <- rnorm(n, mean = 0, sd = 1)
  test1 <- t.test(data1)

  if (test1$p.value < 0.05 || test1$p.value > p_upper_threshold) {
    return(test1$p.value)
  } else {
    data2 <- rnorm(n, mean = 0, sd = 1)
    test2 <- t.test(c(data1, data2))
    return(test2$p.value)
  }
}

set.seed(123)  
n_simulations <- 20000  

thresholds <- c(0.5, 0.75, 1)  
results <- sapply(thresholds, function(threshold) {
  significant_results <- sum(replicate(n_simulations, double.sample(threshold) < 0.05))
  proportion_significant <- significant_results / n_simulations
  return(proportion_significant)
})

names(results) <- paste("Threshold:", thresholds)
results
 Threshold: 0.5 Threshold: 0.75    Threshold: 1 
        0.07790         0.08115         0.08290 

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

The false positive rate is inflated across all thresholds. This kind of data-dependent policy can undermine the statistical validity of research findings. Findings may be the result of inflated false positives rather than true effects, which is bad.