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

options(repos = c(CRAN = "https://cran.rstudio.com"))
install.packages("readr")

The downloaded binary packages are in
    /var/folders/cn/w7csh2_j6wbcb97zpfxmdgq00000gn/T//RtmpG64Sb9/downloaded_packages
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.

install.packages("directlabels")

The downloaded binary packages are in
    /var/folders/cn/w7csh2_j6wbcb97zpfxmdgq00000gn/T//RtmpG64Sb9/downloaded_packages
library(ggplot2)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(directlabels)
unique_ages <- fvs %>%
  group_by(subid) %>%
  summarize(age = unique(age))

# Plot histogram using ggplot
ggplot(unique_ages, aes(x = age)) +
  geom_histogram(binwidth = 1,color = "black", fill = "grey") +
  scale_x_continuous(breaks = seq(from = floor(min(unique_ages$age)), 
                                  to = ceiling(max(unique_ages$age)), 
                                  by = 1))+
  labs(x = "Age (months)", y = "Count")

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.5) +  
  geom_smooth(method = "loess", se = FALSE) + 
  geom_smooth(method = "lm", linetype="dotted")+
  labs(
    x = "Age",
    y = "Hand Looking",
    color = "Condition") +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text = element_text(size = 12),
    axis.title = element_text(size = 14)
  )
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

Older children showed increased hand-looking time. The rate of increase in the faces_plus condition (complex background, kids and adults) is higher than that in the face_medium condition (kids played on a white background).

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

I would perform a mixed-effects linear regression analysis.

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.

# Counter for significant results
significant_results <- 0

# Conducting 10,000 t-tests
for (i in 1:10000) {
  # Generate random sample from normal distribution
  sample <- rnorm(30, mean = 0, sd = 1)
  
  # Perform t-test
  t_test_result <- t.test(sample, mu = 0)
  
  # Check if the result is significant
  if (t_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.0519

Next, do this using the replicate function:

# Conducting 10,000 t-tests using replicate
p_values <- replicate(10000, {
  sample <- rnorm(30, mean = 0, sd = 1)
  t_test_result <- t.test(sample, mu = 0)
  t_test_result$p.value
})

# Calculate the proportion of significant results
proportion_significant <- sum(p_values < 0.05) / 10000
proportion_significant
[1] 0.0516

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

Both simulations showed false-positive rate very close to what we intended for.

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() {
  # Number of observations for each experiment
  num_observations <- 30

  # Perform the initial experiment
  initial_sample <- rnorm(num_observations, mean = 0, sd = 1)
  initial_test <- t.test(initial_sample, mu = 0)

  # Initial decision based on p-value
  if (initial_test$p.value < 0.05 || initial_test$p.value > 0.25) {
    # Stop and return the initial p-value
    return(initial_test$p.value)
  } else {
    # Run additional experiment
    additional_sample <- rnorm(num_observations, mean = 0, sd = 1)
    combined_sample <- c(initial_sample, additional_sample)
    combined_test <- t.test(combined_sample, mu = 0)

    # Return the combined p-value
    return(combined_test$p.value)
  }
}

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

result = replicate(10000, double.sample()  < 0.05)
proportion = sum (result)/10000
proportion
[1] 0.0702

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

Yes, there is an inflation. The false positive increased from around 0.05 to 0.07

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(x) {
  # Number of observations for each experiment
  num_observations <- 30

  # Perform the initial experiment
  initial_sample <- rnorm(num_observations, mean = 0, sd = 1)
  initial_test <- t.test(initial_sample, mu = 0)

  # Initial decision based on p-value
  if (initial_test$p.value < x & initial_test$p.value > 0.05) {
    # Stop and return the initial p-value
    additional_sample <- rnorm(num_observations, mean = 0, sd = 1)
    combined_sample <- c(initial_sample, additional_sample)
    combined_test <- t.test(combined_sample, mu = 0)

    # Return the combined p-value
    return(combined_test$p.value)
   
  } else {
    # Run additional experiment
     return(initial_test$p.value)
  }
}
  #doubles the sample whenever their pvalue is not significant, but it's less than 0.5.
result = replicate(30000, double.sample(0.5) < 0.05)
proportion = sum (result)/30000
proportion
[1] 0.07706667
 #doubles the sample whenever their pvalue is not significant, but it's less than 0.75.
result = replicate(30000, double.sample(0.75) < 0.05)
proportion = sum (result)/30000
proportion
[1] 0.0818
#doubles their sample whenever they get ANY pvalue that is not significant.
result = replicate(30000, double.sample(1) < 0.05)
proportion = sum (result)/30000
proportion
[1] 0.08316667

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

The false positive rate seemed to increase as the researcher was more optimistic. Overall, I think this kind of data-dependent policy is bad - only making the likelihood of getting a false positive effect higher.