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 packages ──────────────────────── tidyverse 1.3.0 ──
## ✔ ggplot2 3.2.1     ✔ purrr   0.3.3
## ✔ tibble  2.1.3     ✔ dplyr   0.8.3
## ✔ tidyr   1.0.0     ✔ stringr 1.4.0
## ✔ readr   1.3.1     ✔ forcats 0.4.0
## ── Conflicts ─────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
fvs <- read_csv("data/FVS2011-hands.csv")
## Parsed with column specification:
## cols(
##   subid = col_double(),
##   age = col_double(),
##   condition = col_character(),
##   hand.look = col_double()
## )

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.

# Remove duplicate rows of the dataframe using subject ID

newdata <- fvs %>% 
distinct(subid, .keep_all= TRUE)

# Now create the histogram
  ggplot(newdata, aes(x=age)) + 
  geom_histogram(binwidth = 1) 

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.

# Make the scatterplot

p <- ggplot(fvs, mapping = aes(x = age, y = hand.look, color = condition)) + # color code by scene condition
  geom_smooth(aes(x = age, y = hand.look), method = "lm") + # add the smoothing lines
   geom_point()

# Label the graph with title and the x-axis and y-axis

p + labs(y = "Hand Looking", 
         x = "Participant Age (In Months)", 
         title = "Hand Looking As a Function of Age") 

What do you conclude from this pattern of data?

Under the age of about 10 months, infants look at hands in both types of scenes for about the same amount of time. At around 15 months, babies start spending more time looking at movies with complex backgrounds than simpler scenes with a white background.

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

You could do a regression to see if age predicts time spent looking at hands and you could separate it by condition.

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  # Number of simulations

p.values <- rep(NA, N.Sim) # Place-holder vector to update with simulation results

for (i in 1:N.Sim) { # Define the action for each loop
  
  Sample.Data <- rnorm(30, mean = 0, sd = 1) # Generate 10 observations from the standard normal dist
  Test <- t.test(Sample.Data) # Conduct a one-sample t.test on the sample data
  Current.p.value <- Test$p.value # Extract the p-value from the test
  
  p.values[i] <- Current.p.value # Add the p-value to the p.values vector
  
  }
  
p.values.lt05 <- p.values <= .05 # Create a new vector indicating which p.values are less than .05
Final.Result <- mean(p.values.lt05)  # Final result! Should be close to .05
Final.Result
## [1] 0.0511

Next, do this using the replicate function:

tps <- replicate(10000, t.test(rnorm(30, mean = 0, sd = 1)), simplify=FALSE)   # Run the simulation
pvalues <- sapply(tps, function(x) x$p.value) # 

p.values.lt05 <- pvalues <= .05 # Create a new vector indicating which p.values are less than .05
Final.Result <- mean(p.values.lt05)  # Final result! Should be close to .05
Final.Result
## [1] 0.0449

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

They’re both pretty close to .05. First simulation using the for loop was .0514 (so, elevated) and the second exercise using the replicate function was (.0562), so also slightly higher than the .05 rate we might hope 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(x) {
trial.1 <-rnorm(x)
Test.start<-t.test(trial.1)
Current.p.value <- Test.start$p.value
    
if (Current.p.value > 0.05 & Current.p.value < 0.25)
  {
    trial.2 <- append(trial.1, rnorm(30)) 
    Test.next <- t.test(trial.2)
    Current.p.value <- Test.next$p.value       # Add the p-value to the p.values vector
  }
  invisible(Current.p.value)    # returns final p-value
}

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

num <-c(10000)              # assign the vector
counter <- 0
for (i in 1:10000)
  {
  num[i] <- double.sample(30)
  if (num[i]<0.05)
  {
    counter<-counter+1
  }
}

print(counter/10000)
## [1] 0.0721

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

There is an inflation. In my simulations this number bounces around between about .069 and .0728, so we’re getting false positives approximatley 7% of the time, when we should be seeing them about 5%, but this is a 50% increase over the original conditions so it’s pretty bad when we quantify it like that.

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:

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) {
trial.1 <-rnorm(x)
Test.start<-t.test(trial.1)
Current.p.value <- Test.start$p.value
    
if (Current.p.value > 0.05 & Current.p.value < 0.5)
  {
    trial.2 <- append(trial.1, rnorm(30)) 
    Test.next <- t.test(trial.2)
    Current.p.value <- Test.next$p.value       # Add the p-value to the p.values vector
  }
  invisible(Current.p.value)    # returns final p-value
}

num <-c(10000)              # assign the vector
counter <- 0
for (i in 1:10000)
  {
  num[i] <- double.sample(30)
  if (num[i]<0.05)
  {
    counter<-counter+1
  }
}

print(counter/10000)
## [1] 0.0815
double.sample <- function(x) {
trial.1 <-rnorm(x)
Test.start<-t.test(trial.1)
Current.p.value <- Test.start$p.value
    
if (Current.p.value > 0.05 & Current.p.value < 0.75)
  {
    trial.2 <- append(trial.1, rnorm(30)) 
    Test.next <- t.test(trial.2)
    Current.p.value <- Test.next$p.value       # Add the p-value to the p.values vector
  }
  invisible(Current.p.value)    # returns final p-value
}

num <-c(10000)              # assign the vector
counter <- 0
for (i in 1:10000)
  {
  num[i] <- double.sample(30)
  if (num[i]<0.05)
  {
    counter<-counter+1
  }
}

print(counter/10000)
## [1] 0.0813
double.sample <- function(x) {
trial.1 <-rnorm(x)
Test.start<-t.test(trial.1)
Current.p.value <- Test.start$p.value
    
if (Current.p.value > 0.05)
  {
    trial.2 <- append(trial.1, rnorm(30)) 
    Test.next <- t.test(trial.2)
    Current.p.value <- Test.next$p.value       # Add the p-value to the p.values vector
  }
  invisible(Current.p.value)    # returns final p-value
}

num <-c(10000)              # assign the vector
counter <- 0
for (i in 1:10000)
  {
  num[i] <- double.sample(30)
  if (num[i]<0.05)
  {
    counter<-counter+1
  }
}

print(counter/10000)
## [1] 0.0842

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

In my opinion the inflation is hugely problematic because double sampling leads to a signifcantly increased rate of false positives (Type 1 error). As the criteria becomes more lax the inflation becomes much worse. By the time we reach the condition of double sampling any p-value we’re getting approaching the line of getting false positives almost(ish) twice as often as our usual criteria (.05), which is arguably already too low.