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

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.4     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ 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
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.

by_agegroup <- fvs |> 
  group_by(subid) |> 
  summarise(sub_age=mean(age))

hist_age <- ggplot(data = by_agegroup, aes(x=sub_age))
hist_age + geom_histogram(binwidth = 1) +
labs(x = "Age (months)", y = "Number of participants")

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$condition <- factor(fvs$condition)

scatter1 <- ggplot(data = fvs, aes(x=age, y=hand.look))
scatter1 + geom_point(aes(color=condition)) + 
  geom_smooth(aes(group = condition, color = condition),  method = "lm") +
  labs(x = "Age (months)", y = "Percentage looking at hands")
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

As children grow older, they look more at hands. This effect is more pronounced with increasing complexity of visual scenes.

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

I would conduct a linear mixed-effects regression, with percentage looking at hands as the dependent variable, the condition and age as the fixed effects, and individual participant variance as a random effect. In addition, as the smoothing lines look to have very different gradients and intercepts, we should be testing the interaction effect too. Our formula would look therefore look like:

hand.look ~ condition + age + condition*age + (1|subid) + error

library(lme4)
Loading required package: Matrix

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

    expand, pack, unpack
handlook.model = lmer(hand.look ~ condition + age + condition*age + (1|subid), data=fvs)

summary(handlook.model)
Linear mixed model fit by REML ['lmerMod']
Formula: hand.look ~ condition + age + condition * age + (1 | subid)
   Data: fvs

REML criterion at convergence: -657.9

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-3.2824 -0.6168 -0.0614  0.4640  3.9945 

Random effects:
 Groups   Name        Variance  Std.Dev.
 subid    (Intercept) 0.0005493 0.02344 
 Residual             0.0024313 0.04931 
Number of obs: 232, groups:  subid, 119

Fixed effects:
                         Estimate Std. Error t value
(Intercept)              0.023014   0.015416   1.493
conditionFaces_Plus     -0.028940   0.019649  -1.473
age                      0.003059   0.001176   2.602
conditionFaces_Plus:age  0.004000   0.001499   2.668

Correlation of Fixed Effects:
            (Intr) cndF_P age   
cndtnFcs_Pl -0.646              
age         -0.944  0.611       
cndtnFcs_P:  0.610 -0.944 -0.646

The lmer reveals that there is a statistically significant effect of age, as well as the interaction effect between age and condition, supporting my conclusion above. The main effect of condition is not statistically significant.

Part 2: Simulation

# First iteration of subsequent 'for' loop

# Sampling 30 numbers with mean 0 and sd 1
allruns <- rnorm (30, mean = 0, sd = 1)

# Running a two-tailed t-test on the sample with mean centered at 0 
alltests <- t.test(allruns, mu = 0)

# Running a logical check to see if t-test was statistically significant at p<0.05
allsigp <- alltests$p.value < 0.05

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.

for (runs in 1:9999)
  {
     sample <- rnorm (30, mean = 0, sd = 1)
     ttest <- t.test(sample, mu = 0)
     sigp <- ttest$p.value < 0.05
     allruns <- cbind(allruns, sample) # storing results of all runs just in case I need to verify the sampling raw data
     alltests <- cbind(alltests,ttest)
     allsigp <- cbind(allsigp,sigp)
}

# With TRUE = 1 and FALSE = 0, mean will give proportion of TRUE values
proportionsig <- mean(allsigp)
print(proportionsig)
[1] 0.0514

Next, do this using the replicate function:

# Create empty matrices to store results
allrepsigp <- matrix(nrow = 1, ncol = 10000)   # To store significance flags

# Perform replicates and store results using replicate
allrepsigp <- replicate(
  10000,
  {
    repsample <- rnorm(30, mean = 0, sd = 1)
    repttest <- t.test(repsample, mu = 0)
    repsigp <- repttest$p.value < 0.05
  }
)

# Calculate the proportion of statistically significant t-tests
proportionrepsig <- mean(allrepsigp)
print(proportionrepsig)
[1] 0.0503

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

Both methods yield results pretty close to 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.

# Create empty matrices to store results
bothsamps <- matrix(nrow = 30, ncol = 0)  # To store generated samples
allsampruns <- matrix(nrow = 30, ncol = 0)  # To store all sample runs
allsamptests <- matrix(nrow = 10, ncol = 0)  # To store t-test results
allsampsigp <- matrix(nrow = 1, ncol = 0)  # To store significance flags


double.sample <- function() {
  samplerun <- rnorm(30, mean = 0, sd = 1)
  sampletest <- t.test(samplerun, mu = 0)
  samplesig <- sampletest$p.value < 0.05
  
  if (sampletest$p.value > 0.05 || sampletest$p.value < 0.25) {
    sample2 <- rnorm(30, mean = 0, sd = 1)
    bothsamps <- cbind(bothsamps, sample2)
    bothsamptest <- t.test(bothsamps, mu = 0)
    bothsigp <- bothsamptest$p.value < 0.05
    
    allsampruns <- cbind(allsampruns, sample2)
    allsamptests <- cbind(allsamptests,bothsamptest)
    allsampsigp <- cbind(allsampsigp,bothsigp)
  }
  else 
  {
     allsampruns <- cbind(allsampruns, samplerun)
     allsamptests <- cbind(allsamptests,sampletest)
     allsampsigp <- cbind(allsampsigp,samplesig)
  }
}

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

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

# Calculate the proportion of statistically significant t-tests
proportionsampsig <- mean(doublesamplereps)
print(proportionsampsig)
[1] 0.0508

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

There appears not to be an inflation of false positives, which is quite counterintuitive to me.

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.

# function now accepts upper p value as an argument
double.sample.2 <- function(uppervalue) {
  samplerun <- rnorm(30, mean = 0, sd = 1)
  sampletest <- t.test(samplerun, mu = 0)
  samplesig <- sampletest$p.value < 0.05
  
  if (sampletest$p.value > 0.05 || sampletest$p.value < uppervalue) {
    sample2 <- rnorm(30, mean = 0, sd = 1)
    bothsamps <- cbind(bothsamps, sample2)
    bothsamptest <- t.test(bothsamps, mu = 0)
    bothsigp <- bothsamptest$p.value < 0.05
    
    allsampruns <- cbind(allsampruns, sample2)
    allsamptests <- cbind(allsamptests,bothsamptest)
    allsampsigp <- cbind(allsampsigp,bothsigp)
  }
  else 
  {
     allsampruns <- cbind(allsampruns, samplerun)
     allsamptests <- cbind(allsamptests,sampletest)
     allsampsigp <- cbind(allsampsigp,samplesig)
  }
}

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.
moresampling1 <- replicate(1000000, double.sample.2(0.5))
print(mean(moresampling1))
[1] 0.050247
# The researcher doubles the sample whenever their pvalue is not significant, but it's less than 0.75.
moresampling2 <- replicate(1000000, double.sample.2(0.75))
print(mean(moresampling2))
[1] 0.050086
# The research doubles their sample whenever they get ANY pvalue that is not significant.
moresampling3 <- replicate(1000000, double.sample.2(uppervalue = Inf))
print(mean(moresampling3))
[1] 0.050184

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

I honestly thought that it would be really bad, but the 1 million replications show that the proportion of true t-tests still hovers really close to 0.05… Unless there’s something wrong with my code?