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.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.4     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   2.0.1     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
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(dplyr)
fvs.distinct <- distinct(fvs, subid, .keep_all = TRUE) 

ggplot(fvs.distinct, aes(x=age))+
  geom_bar(width = 0.1)
## Warning: position_stack requires non-overlapping x intervals

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)) + 
  geom_point() + 
  facet_grid(~condition) +
  geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

What do you conclude from this pattern of data?

The relationship between age and the infants’ looking to hands in moving scenes, hereafter “hand.look”, is positive and linear for the Faces_Medium condition, whereas the same relationship is curvilinear for the Faces_Plus condition.

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

To quantify these differences, I would divide the ages into three sections – (i) up to 10 months, (ii) between 10 and 20 months, and (iii) 20 months and above – and conduct t-tests comparing Faces_Medium and Faces_Plus conditions conditional on age groups.

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.

loop_simulation <- c()

for (i in 1:10000) {
  sample <- rnorm(n = 30, mean = 0, sd =1)
  
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  loop_simulation[i] <- ifelse(test.result$p.value < 0.05, 1, 0)

}

prop_significant <- sum(loop_simulation)/10000

The proportion of significant results is 0.051.

Next, do this using the replicate function:

replicate_function <- function(x){
  
  sample <- rnorm(n = 30, mean = 0, sd =1)
  
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  return(ifelse(test.result$p.value < 0.05, 1, 0))
}  
  
loop_simulation_replicate <- replicate(10000, replicate_function(x))

proportion_replicate<- sum(loop_simulation_replicate)/10000

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

This compares similarly to the intended false-positive rate of alpha = 0.05.

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 () {
  
  sample <- rnorm(n = 30, mean = 0, sd =1)
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  if (test.result$p.value < 0.25 & test.result$p.value > 0.05) {
      sample.2 <- rnorm(n = 30, mean = 0, sd =1)
      
      sample.3 <- append(sample, sample.2)
      
      test.result <- t.test(sample.3, 
                        alternative = c("two.sided"), 
                        mu = 0)
      return(ifelse(test.result$p.value < 0.05, 1, 0))
  }
  
  else if (test.result$p.value < 0.05){
    return(ifelse(test.result$p.value < 0.05, 1, 0))
  }
  
  else (return(ifelse(test.result$p.value < 0.05, 1, 0)))
}

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

loop_final <- replicate(10000, double.sample())

falsepositive_final <- sum(loop_final)/10000

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

Yes, there is an inflation of false positives. We get 0.0771, which is higher in proportion than the proportion using the replicate function 0.0518 or the proportion using the for loop 0.0505

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.

#first scenario - double whenver pvalue is less than 0.5

double.sample.first <- function () {
  
  sample <- rnorm(n = 30, mean = 0, sd =1)
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  if (test.result$p.value < 0.5 & test.result$p.value > 0.05) {
      sample.2 <- rnorm(n = 30, mean = 0, sd =1)
      
      sample.3 <- append(sample, sample.2)
      
      test.result <- t.test(sample.3, 
                        alternative = c("two.sided"), 
                        mu = 0)
      return(ifelse(test.result$p.value < 0.05, 1, 0))}
  
  else (return(ifelse(test.result$p.value < 0.05, 1, 0)))
}

falsepos_first <- sum(replicate(10000, double.sample.first()))/10000

#second scenario

double.sample.second <- function () {
  
  sample <- rnorm(n = 30, mean = 0, sd =1)
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  if (test.result$p.value < 0.75 &  test.result$p.value > 0.05) {
      sample.2 <- rnorm(n = 30, mean = 0, sd =1)
      sample.3 <- append(sample, sample.2)
      test.result <- t.test(sample.3, 
                        alternative = c("two.sided"), 
                        mu = 0)
      return(ifelse(test.result$p.value < 0.05, 1, 0))
  }
  
  else (return(ifelse(test.result$p.value < 0.05, 1, 0)))
}
falsepos_second <- sum(replicate(10000, double.sample.second()))/10000

#third scenario
double.sample.third <- function () {
  
  sample <- rnorm(n = 30, mean = 0, sd =1)
  test.result <- t.test(sample, 
                        alternative = c("two.sided"), 
                        mu = 0)
  
  if (test.result$p.value > 0.05) {
      sample.2 <- rnorm(n = 30, mean = 0, sd =1)
      sample.3 <- append(sample, sample.2)
      test.result <- t.test(sample.3, 
                        alternative = c("two.sided"), 
                        mu = 0)
      return(ifelse(test.result$p.value < 0.05, 1, 0))
  }
  
  else (return(ifelse(test.result$p.value < 0.05, 1, 0)))
}
falsepos_third <- sum(replicate(10000, double.sample.third()))/10000

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

Based on this simulation, there seems to be the highest false positive rate for the first scenario (0.0809), followed by the rate for the second scenario (0.0796) and the rate for the third scenario (0.0871). The more we depend on the data, that is the more we make the decision to double the sample based on the results of the sample, it is more likely that we run into false positive cases.