Psych 251 PS4: Simulation + Analysis

Published

December 31, 2018

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   4.0.0     ✔ tibble    3.2.1
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── 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
library(ggplot2)
theme_set(theme_classic())
library(lme4)
Loading required package: Matrix

Attaching package: 'Matrix'

The following objects are masked from 'package:tidyr':

    expand, pack, unpack

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

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.

# keep one row per kid
df_ages <- fvs %>% 
        distinct(subid, .keep_all = TRUE)

# histogram of ages
ggplot(df_ages, aes(x = age)) +
        geom_histogram(bins = 15)

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.4) +
        geom_smooth(method = 'lm') +
        labs(x = 'age (months)',
             y = 'looking to hands (proportion)',
             title = "infants' looking to hands in moving scenes") +
        theme(axis.text.x=element_text(size = 14),
              axis.text.y=element_text(size = 14),
              axis.title.x=element_text(size = 16),
              axis.title.y=element_text(size = 16),
              plot.title=element_text(size = 20, hjust = 0.5),
              legend.position='none') +
        scale_x_continuous(breaks = seq(0, 30, by = 5)) +
        geom_label(x=26, y=0.13, label="medium", color = '#D99304', size = 5) + 
        geom_label(x=26, y=0.21, label="plus", color = '#434A9C', size = 5) +
        scale_color_manual(values=c('#D99304', '#434A9C'))
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

It appears that there is an interaction between age and whether infants watched the video with the more complex visual scene as opposed to the simpler one on the amount of time which they spent looking at hands.

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

In order to test for this interaction effect, I would compare two mixed effects models predicting proportion of time looking at hands: one with condition, age, their interaction, and a random intercept for participant, and the other the same but without the interaction. See my analysis below (the age x condition interaction does appear to be a significant predicor):

# more complex model
fit.augmented <- lmer(hand.look ~ condition * age + (1 | subid), data = fvs)

# null model
fit.compact <- lmer(hand.look ~ condition + age + (1 | subid), data = fvs)

# compare model fit
anova(fit.augmented, fit.compact)
refitting model(s) with ML (instead of REML)
Data: fvs
Models:
fit.compact: hand.look ~ condition + age + (1 | subid)
fit.augmented: hand.look ~ condition * age + (1 | subid)
              npar     AIC     BIC logLik deviance  Chisq Df Pr(>Chisq)   
fit.compact      5 -681.79 -664.56 345.89  -691.79                        
fit.augmented    6 -686.78 -666.10 349.39  -698.78 6.9904  1   0.008195 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

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.

# set seed
set.seed(1)

# number of tests to run
num_reps = 10000

# sample size
sample_size = 30

# initialize number of tests found to be significant
significant = 0

for (i in 1:num_reps) {
        # randomly sample 30 points
        sample <- rnorm(n = sample_size, mean = 0, sd = 1)
        # run t-test
        test <- t.test(sample, mu = 0, alternative = 'two.sided')
        # check if significant results
        if (test$p.val < .05) {
                significant = significant + 1
        }
}

# calculate false positive rate
false_pos_rate = significant / num_reps
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.0502"

Next, do this using the replicate function:

# set seed
set.seed(1)

# set number of replications
num_replications = 10000

# write function to simulate data and run tests
simulate = function(sample_size, alpha, mean) {
        sample <- rnorm(n = sample_size, mean = mean, sd = 1)
        test <- t.test(sample, mu = 0, alternative = 'two.sided')
        p_value <- test$p.val
        if (p_value < alpha) {
                return(1)
        } else {
                return(0)
        }
}

# run simulation and tests
positives <- replicate(n = num_replications,
                    simulate(sample_size, 0.05, 0))

# calculate false positive rate
false_pos_rate = sum(positives) / num_replications
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.0502"

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

This is very close to the intended false positive rate.

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.

# function to run optional stopping simulation
double.sample <- function(sample_size, min_pval, max_pval) {
        sample <- rnorm(n = sample_size, mean = mean, sd = 1)
        test <- t.test(sample, mu = 0, alternative = 'two.sided')
        p_value <- test$p.val
        while (p_value < max_pval & p_value > min_pval) {
                sample <- rnorm(n = sample_size, mean = mean, sd = 1)
                test <- t.test(sample, mu = 0, alternative = 'two.sided')
                p_value <- test$p.val
        }
        return(p_value)
}

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

# set seed
set.seed(1)

# run optional stopping simulation
positives <- replicate(n = num_replications, simulate(sample_size, 0.05, 0.25))

# calculate false positive rate
false_pos_rate = sum(positives) / num_replications
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.2609"

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

There is a large inflation of false positives rates – it is 5x the original rate!

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.

# Re-run for p-values: (0.05, 0.5)
positives <- replicate(n = num_replications, simulate(sample_size, 0.05, 0.5))

# calculate false positive rate
false_pos_rate = sum(positives) / num_replications
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.7549"
# Re-run for p-values: (0.05, 0.5)
positives <- replicate(n = num_replications, simulate(sample_size, 0.05, 0.75))

# calculate false positive rate
false_pos_rate = sum(positives) / num_replications
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.9787"
# Re-run for p-values: (0.05, 0.5)
positives <- replicate(n = num_replications, simulate(sample_size, 0.05, 1))

# calculate false positive rate
false_pos_rate = sum(positives) / num_replications
print(paste('false positive rate:', false_pos_rate))
[1] "false positive rate: 0.9999"

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

As the researcher becomes more optimistic and increases the upper bound on their sample re-run criteria, the false positive rate converges to one. This is pretty bad! No matter the data, if we keep increasing our sample until the results are significant, we will eventually find what we’re looking for…