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)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ dplyr   1.0.10
## ✔ tibble  3.1.8      ✔ stringr 1.4.1 
## ✔ tidyr   1.2.1      ✔ forcats 0.5.2 
## ✔ purrr   0.3.4      
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(dplyr)

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.
fvs
## # A tibble: 232 × 4
##    subid   age condition    hand.look
##    <dbl> <dbl> <chr>            <dbl>
##  1     2  3.16 Faces_Medium    0.0319
##  2    93  5.03 Faces_Medium    0.119 
##  3    29  5.85 Faces_Medium    0.0921
##  4    76  5.85 Faces_Medium    0.130 
##  5    48  6.08 Faces_Medium    0.0138
##  6   101  6.15 Faces_Medium    0.0438
##  7    67  6.54 Faces_Medium    0.0242
##  8    73  6.64 Faces_Medium    0.0669
##  9    69  6.90 Faces_Medium    0.0314
## 10    84  7.23 Faces_Medium    0.105 
## # … with 222 more rows

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.

fvs %>% group_by(subid) %>% 
  ggplot(aes(x=age)) + 
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

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.

fvs %>% group_by(subid) %>%
  ggplot(aes(x = age, y = hand.look, color = condition)) +
  labs(title = "Handlooking by Age and Condition", x = "Age", y = "Hand Looking Time") +
  geom_point() +
  geom_smooth(se = FALSE) #removes standard error line shading (a note for me later)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

  #geom_line() #it's not this one

What do you conclude from this pattern of data?

There seems to possibly be a relationship between hand looking and Faces_Medium but possibly no relationship between hand looking and Faces_Plus. For Faces_Plus though, there seems to be some outliers so removing these may change the result.

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

A linear regression would be helpful to see if there’s a linear pattern between age and hand-looking.Then use a t-test to quanitfy possible differences.

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.

num_t_tests <- 10000
num_false_positives <- 0

for (i in 1:num_t_tests) {
  data <- rnorm(30)
  
  p <- t.test(data)["p.value"]
  if (p < 0.05) {
    num_false_positives <- num_false_positives + 1
  }
}
print(num_false_positives / 10000) #false positive rate!
## [1] 0.0518

Next, do this using the replicate function:

num_false_positives <- sum(replicate(10000, t.test(rnorm(30))["p.value"] < 0.05))
print(num_false_positives / 10000)
## [1] 0.049

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

Pretty similar!

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() {
  new_data <- rnorm(30)
  p <- t.test(new_data)["p.value"]

  if(0.05 < p && p <0.25 )
    {new_data_double <- rnorm(30)} 
  else {new_data_double <- NULL}
    return (union(new_data, new_data_double))
} 

double.sample()
##  [1] -0.34812307 -0.70597922 -1.71785413 -0.01880306 -1.12026003 -0.76717922
##  [7]  1.36981783  1.87721708  0.36300084 -0.69131614 -0.62063084 -0.66938702
## [13]  1.04194260 -0.85248035 -0.78855601 -1.90702696  0.62548182  2.82677167
## [19] -0.75636602  0.07646413  0.14473599 -0.93102010  2.38864920  1.95466325
## [25]  0.37609807  0.83962212 -0.23442797  1.60489792 -0.50446054  1.08968134

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

num_false_positives <- replicate(10000, t.test(double.sample())["p.value"])
sum(num_false_positives < 0.05)/10000
## [1] 0.0692

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

Yes the false positives go up by 2%!

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.

#The researcher doubles the sample whenever their pvalue is not significant, but it's less than 0.5.

double.sample2 <- function() {
  new_data <- rnorm(30)
  p <- t.test(new_data)["p.value"]

  if(p < 0.5 )
    {new_data_double <- rnorm(30)} 
  else {new_data_double <- NULL}
    return (union(new_data, new_data_double))
} 

num_false_positives <- replicate(10000, t.test(double.sample2())["p.value"])
sum(num_false_positives < 0.05)/10000
## [1] 0.0476
#The researcher doubles the sample whenever their pvalue is not significant, but it's less than 0.75.

double.sample3 <- function() {
  new_data <- rnorm(30)
  p <- t.test(new_data)["p.value"]

  if(p < 0.75 )
    {new_data_double <- rnorm(30)} 
  else {new_data_double <- NULL}
    return (union(new_data, new_data_double))
} 

num_false_positives <- replicate(10000, t.test(double.sample3())["p.value"])
sum(num_false_positives < 0.05)/10000
## [1] 0.0494
#The research doubles their sample whenever they get ANY pvalue that is not significant.

double.sample4 <- function() {
  new_data <- rnorm(30)
  p <- t.test(new_data)["p.value"]

  if(p < 10 )
    {new_data_double <- rnorm(30)} 
  else {new_data_double <- NULL}
    return (union(new_data, new_data_double))
} 

num_false_positives <- replicate(10000, t.test(double.sample4())["p.value"])
sum(num_false_positives < 0.05)/10000
## [1] 0.054

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

It is possible to get a significant value if you continue to add participents at null results after the initally planned number of participants. Data-depednent experiemnt policies can produce way more false positives than non data-driven policies.