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

#install.packages("readr")
library(readr)
setwd("/Users/milka/Documents/GitHub/psyc 251/problem_sets/")
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(ggplot2)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ stringr   1.5.2
✔ forcats   1.0.1     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.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
fvs_unique <- fvs %>% 
  distinct(subid, .keep_all = TRUE)

ggplot(fvs_unique, aes(x = age)) +
  geom_histogram(binwidth = 1) +
  labs(
    title = "Histogram of Child Ages",
    x = "Age (years)",
    y = "Count"
  ) +
  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, size = 2) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(
    x = "Age (years)",
    y = "Hand Looking",
    color = "Condition"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    legend.position = "right"
  )
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

With age, participants spend higher proportion of time looking at hands and the effect is stronger for more complex backgrounds with both adults and kids, which suggest that they give more attention to those videos.

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

For each condition, I would fit a linear regression of hand looking as a function of age and test whether the slope differs significantly from zero. I would test whether the effect of age on hand looking differs by condition by including an age × condition interaction in a linear model and assessing its significance with ANOVA.I would compare hand looking between conditions at specific ages using t-tests, taking into account multiple comparisons.

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.

n_sim <- 10000
p_values <- numeric(n_sim)
for (i in 1:n_sim) {
  sample_data <- rnorm(30, mean = 0, sd = 1)
  test <- t.test(sample_data, mu = 0)
  p_values[i] <- test$p.value
}

mean(p_values < 0.05)
[1] 0.0491

Next, do this using the replicate function:

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

mean(p_values < 0.05)
[1] 0.0516

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

The results match the expected false-positive rate (α = 0.05), as we would expect about 5% of tests to be significant by chance when the null hypothesis is true.

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() {
}

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

double.sample <- function() {
  data1 <- rnorm(30, mean = 0, sd = 1)
  test1 <- t.test(data1, mu = 0)
  p1 <- test1$p.value
  
  # stopping rules
  if (p1 < 0.05 || p1 > 0.25) {
    return(p1)  
  } else {
    #optional 30 more observations
    data2 <- rnorm(30, mean = 0, sd = 1)
    combined <- c(data1, data2)
    
    test2 <- t.test(combined, mu = 0)
    return(test2$p.value)
  }
}
double.sample()
[1] 0.7168313

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

Yes, the optional stopping does increase false positives largely! It increases significantly

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 = 0.25) {
  data1 <- rnorm(30, mean = 0, sd = 1)
  p1 <- t.test(data1, mu = 0)$p.value
  if (p1 < 0.05 || p1 > p_upper) {
    return(p1)  # stop
  } else {
    data2 <- rnorm(30, mean = 0, sd = 1)
    combined <- c(data1, data2)
    return(t.test(combined, mu = 0)$p.value)
  }
}


n_sim <- 10000


# Scenario 1: double if p < 0.5
results1 <- replicate(n_sim, double.sample(p_upper = 0.5))
mean(results1 < 0.05)
[1] 0.0815
# Scenario 2: double if p < 0.75
results2 <- replicate(n_sim, double.sample(p_upper = 0.75))
mean(results2 < 0.05)
[1] 0.0868
# Scenario 3: double if p < 1 (i.e., always double if not significant)
results3 <- replicate(n_sim, double.sample(p_upper = 1))
mean(results3 < 0.05)
[1] 0.0831

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

This kind of data-dependent policy isn’t that bad overall. Interestingly, it’s actually worse to adjust the sample size when the p-value is very close to 0.05, which seems paradoxical, because a scientist might think they’re right at the threshold and just need a little more data to reach significance - they might think they dont have enough power.