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

library(tidyverse) # for data munging
── 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   3.5.1     ✔ 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(knitr) # for kable table formating
library(haven) # import and export 'SPSS', 'Stata' and 'SAS' Files
library(readxl) # import excel files
library(lme4)
Loading required package: Matrix

Attaching package: 'Matrix'

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

    expand, pack, unpack
# #optional packages/functions:
library(afex) # anova functions
************
Welcome to afex. For support visit: http://afex.singmann.science/
- Functions for ANOVAs: aov_car(), aov_ez(), and aov_4()
- Methods for calculating p-values with mixed(): 'S', 'KR', 'LRT', and 'PB'
- 'afex_aov' and 'mixed' objects can be passed to emmeans() for follow-up tests
- Get and set global package options with: afex_options()
- Set sum-to-zero contrasts globally: set_sum_contrasts()
- For example analyses see: browseVignettes("afex")
************

Attaching package: 'afex'

The following object is masked from 'package:lme4':

    lmer
library(ez) # anova functions 2
library(emmeans)
Welcome to emmeans.
Caution: You lose important information if you filter this package's results.
See '? untidy'
# library(scales) # for plotting
# std.err <- function(x) sd(x)/sqrt(length(x)) # standard error

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.

# Use (distinct) to remove duplicate rows
fvs.graph = fvs %>% 
  distinct(subid,
           .keep_all = TRUE) # ensures keeps necessary data 

# Creae histogram using fvs.graph
ggplot(data = fvs.graph,
       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.

# Use ggplot to create base graph
ggplot(data = fvs,
       aes(x = age, # x-axis
           y = hand.look, # y-axis
           color = factor(x = condition, # color/group by condition (change labels for ease of reading)
                          levels = c("Faces_Medium", "Faces_Plus"),
                          labels = c("Face Medium", "Faces Plus"))
       )) + 
  
  # Add geom_point to show data points, change transparency to 0.8
  geom_point(alpha = 0.8) +
  
  # Add regression lines using lm and standard error bands
  geom_smooth(method = "lm", 
              se = TRUE) +
  
   # Change x-axis label, y-axis label, add caption
  labs(x = "Age",
       y = "Hand Looking",
       title = "Hand Looking as a Function of Age and Condition") +
  
  # Change legend title
  guides(color = guide_legend(title = "Condition")) +

  # Use black/white theme
  theme_bw() + 
  
   # Set y_axis scales
  scale_x_continuous(limits = c(0, 30),
                     expand = c(0, 0),
                    breaks = seq(0, 30, by = 5)) +
  
  # Center the title
  theme(plot.title = element_text(hjust = 0.5))
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

Based on this pattern of data, I conclude that as age increases, hand looking also increases. However, the rate of increase is higher for participants in the faces medium condition than for participants in the faces plus condition.

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

I would regress hand looking on age, condition, and the age x condition interaction. The last term, age x condition would be particularly useful to test my conclusion from above.

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 for reproducibility
set.seed(1234)

# Set parameters
n_samples = 10000
sample_size= 30

# Create empty dataframe to store results (column 1 is sample number, column 2 is p.value)
output = tibble(sample_number = 1:n_samples,
  p.value = numeric(n_samples))

# Use for loop 10,000 times
for (i in 1:n_samples) {
  
  # Create data 
  data = rnorm(n = sample_size,
            mean = 0, # mean
            sd = 1)  # standard deviation

  # run t-test and extract p.value
  p.value = t.test(data)$p.value
  
  # Add p.value to output
  output$p.value[i] = p.value
}

# Add "1" to indicate if p < .01, 0 if not
output = output %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculate proportion of results 
output %>% 
  summarize(proportion_results = sum((output$significance)/n_samples))
# A tibble: 1 × 1
  proportion_results
               <dbl>
1             0.0488

Next, do this using the replicate function:

# Set seed for reproducibility
set.seed(1234)

# Set parameters
n_samples = 10000
sample_size = 30

# Use replicate
d.results = replicate(n = n_samples,
                      expr = t.test(rnorm(n = sample_size, mean = 0, sd = 1))$p.value) %>% 
  data.frame() %>% # create dataframe
    rename("p.value" = ".") 
  
# Add "1" to indicate if p < .01, 0 if not
d.results = d.results %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculate proportion of results 
d.results %>% 
  summarize(proportion_results = sum((d.results$significance)/n_samples))
  proportion_results
1             0.0488

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

The rate of 0.048 is slightly below the false-positive rate of 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.

# Set seed for reproducibility
set.seed(1234)

# Set parameters
sample_size = 30

# Create function
double.sample <- function() {
  # Create data
  data = rnorm(n = sample_size, mean = 0, sd = 1)
  
  # Calculate p.value
  p.value = t.test(data)$p.value
  
  # Use if to check p.value 
  if (p.value > 0.05 & p.value < 0.25) {
    data.new = rnorm(n = 30, mean = 0, sd = 1)
    data.final = c(data.new, data)
    return(t.test(data.final)$p.value)
  } else {
    return(p.value)
  }

}

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

# Set seed
set.seed(1234)

# Set parameters
n_samples = 10000

# Use replicate to calculate 
results = replicate(10000, double.sample()) %>% 
  data.frame() %>% # create dataframe
    rename("p.value" = ".") 

# Add "1" to indicate if p < .01, 0 if not
results = results %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculation proportion of results 
answer = results %>% 
  summarize(proportion_results = sum(results$significance)) # 720 times p-value is above 0.05.

# Calculate increase in false positive rate by dividing [number of times obtain significance]/[expected times obtain significance] - 1
final.results = (answer/500)-1
print(final.results)
  proportion_results
1               0.44

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

Yes, there is a moderate inflation of the false-positive rate to 0.072.

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.

# Choice #1 - Researcher doubles sample when p.value is > 0.05 and < .75

# Set parameters
p.value.high = 0.5
p.value.low = 0.05

# Create new double.sample()
double.sample <- function() {
  # Create data
  data = rnorm(n = sample_size, mean = 0, sd = 1)
  
  # Calculate p.value
  p.value = t.test(data)$p.value
  
  # Use if to check p.value 
  if (p.value > p.value.low & p.value < p.value.high) {
    data.new = rnorm(n = 30, mean = 0, sd = 1)
    data.final = c(data.new, data)
    return(t.test(data.final)$p.value)
  } else {
    return(p.value)
  }

}

# Set parameters
n_samples = 10000

# Use replicate to calculate 
results = replicate(10000, double.sample()) %>% 
  data.frame() %>% # create dataframe
    rename("p.value" = ".") 

# Add "1" to indicate if p < .01, 0 if not
results = results %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculation proportion of results 
answer = results %>% 
  summarize(proportion_results = sum(results$significance)) 

# Calculate increase in false positive rate by dividing [number of times obtain significance]/[expected times obtain significance] - 1
final.results = (answer/500)-1
print(final.results)
  proportion_results
1              0.568
# Choice #2 - Researcher doubles sample when p.value is > 0.05 and < .75

# Set parameters
p.value.high = 0.75
p.value.low = 0.05

# Create new double.sample()
double.sample <- function() {
  # Create data
  data = rnorm(n = sample_size, mean = 0, sd = 1)
  
  # Calculate p.value
  p.value = t.test(data)$p.value
  
  # Use if to check p.value 
  if (p.value > p.value.low & p.value < p.value.high) {
    data.new = rnorm(n = 30, mean = 0, sd = 1)
    data.final = c(data.new, data)
    return(t.test(data.final)$p.value)
  } else {
    return(p.value)
  }

}

# Set parameters
n_samples = 10000

# Use replicate to calculate 
results = replicate(10000, double.sample()) %>% 
  data.frame() %>% # create dataframe
    rename("p.value" = ".") 

# Add "1" to indicate if p < .01, 0 if not
results = results %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculation proportion of results 
answer = results %>% 
  summarize(proportion_results = sum(results$significance)) 

# Calculate increase in false positive rate by dividing [number of times obtain significance]/[expected times obtain significance] - 1
final.results = (answer/500)-1
print(final.results)
  proportion_results
1              0.658
# Choice #3 - Researcher doubles sample when p.value is > 0.05 

# Set parameters
p.value.high = 1.00
p.value.low = 0.05

# Create new double.sample()
double.sample <- function() {
  # Create data
  data = rnorm(n = sample_size, mean = 0, sd = 1)
  
  # Calculate p.value
  p.value = t.test(data)$p.value
  
  # Use if to check p.value 
  if (p.value > p.value.low & p.value < p.value.high) {
    data.new = rnorm(n = 30, mean = 0, sd = 1)
    data.final = c(data.new, data)
    return(t.test(data.final)$p.value)
  } else {
    return(p.value)
  }

}

# Set parameters
n_samples = 10000

# Use replicate to calculate 
results = replicate(10000, double.sample()) %>% 
  data.frame() %>% # create dataframe
    rename("p.value" = ".") 

# Add "1" to indicate if p < .01, 0 if not
results = results %>% 
  mutate(significance = if_else(p.value < .05, 1, 0))

# Calculation proportion of results 
answer = results %>% 
  summarize(proportion_results = sum(results$significance)) # 720 times p-value is above 0.05.

# Calculate increase in false positive rate by dividing [number of times obtain significance]/[expected times obtain significance] - 1
final.results = (answer/500)-1
print(final.results)
  proportion_results
1              0.696

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

Based on the simulation, a data-dependent policy does increase the false positive rate quite significantly. The increase ranges from a ~56% to an almost 70% increase in the false positive rate, which is quite substantial.