library(tidyverse)
library(dplyr)Psych 251 PS4: Simulation + Analysis
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.
fvs %>%
distinct(subid, age) %>%
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.
ggplot(fvs, aes(x=age, y=hand.look, color=condition)) +
geom_point() +
geom_smooth(method="lm") +
labs(x="Age in months",
y="Proportion of time looking at hands") +
scale_color_discrete(labels = c("Faces Medium",
"Faces Plus"))`geom_smooth()` using formula = 'y ~ x'
What do you conclude from this pattern of data?
The proportion of time infants spent looking at hands tended to increase with age. This relationship seems stronger for the Faces Plus condition than the Faces Medium condition
What statistical analyses would you perform here to quantify these differences?
Analyze the correlation between age and proportion of time looking at hands and conduct a paired-samples t-test to analyze the difference between two conditions.
Part 2: Simulation
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(123)
num_sims <- 10000
sig_results <- numeric(num_sims) # store TRUE/FALSE for p < .05
for (i in 1:num_sims) {
# sample 30 observations
x <- rnorm(30, mean = 0, sd = 1)
# perform one-sample t-test
t_out <- t.test(x, mu = 0)
# store whether p-value < .05
sig_results[i] <- t_out$p.value < 0.05
}
# proportion of significant results
mean(sig_results)[1] 0.0465
Next, do this using the replicate function:
set.seed(123)
results <- replicate(
10000,
{
x <- rnorm(30, mean = 0, sd = 1)
t.test(x, mu = 0)$p.value
}
)
# proportion of p-values < .05
mean(results < 0.05)[1] 0.0465
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
The value was slightly below the intended false-positive rate, but pretty close.
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(participants = 30, observations = 1) {
# --- First sample ---
x1 <- rnorm(participants * observations, mean = 0, sd = 1)
p1 <- t.test(x1, mu = 0)$p.value
# Decision rule
if (p1 < 0.05 || p1 > 0.25) {
# stop after first sample
return(list(p.value = p1, n = participants))
}
# Optional second sample (if .05 < p < .25) ---
x2 <- rnorm(participants * observations, mean = 0, sd = 1)
full_sample <- c(x1, x2)
p2 <- t.test(full_sample, mu = 0)$p.value
return(list(p.value = p2, n = participants * 2))
}Now call this function 10k times and find out what happens.
results <- replicate(
10000,
double.sample()$p.value
)
mean(results < 0.05)[1] 0.073
Is there an inflation of false positives? How bad is it?
Yes, the false-positive rate increased to .073. This is a bit less than twice the false-positive rate of the intended false-positive 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.
double.sample <- function(participants = 30, observations = 1, upper_p) {
# --- First sample ---
x1 <- rnorm(participants * observations, mean = 0, sd = 1)
p1 <- t.test(x1, mu = 0)$p.value
# Decision rule
if (p1 < 0.05 || p1 > upper_p) {
# stop after first sample
return(list(p.value = p1, n = participants))
}
# Optional second sample
x2 <- rnorm(participants * observations, mean = 0, sd = 1)
full_sample <- c(x1, x2)
p2 <- t.test(full_sample, mu = 0)$p.value
return(list(p.value = p2, n = participants * 2))
}# Test when upper_p = .5
results <- replicate(
100000,
double.sample(upper_p = .5)$p.value
)
mean(results < 0.05)[1] 0.07932
# Test when upper_p = .75
results <- replicate(
100000,
double.sample(upper_p = .75)$p.value
)
mean(results < 0.05)[1] 0.08349
# Test when upper_p = 1
results <- replicate(
100000,
double.sample(upper_p = 1)$p.value
)
mean(results < 0.05)[1] 0.08182
set.seed(42)
# Function to simulate one double-sample experiment
double.sample <- function(participants = 30, upper_p) {
x1 <- rnorm(participants)
p1 <- t.test(x1, mu = 0)$p.value
# Stop if significant or above upper_p
if (p1 < 0.05 || p1 > upper_p) return(1*(p1 < 0.05))
# Second sample
x2 <- rnorm(participants)
x_full <- c(x1, x2)
p2 <- t.test(x_full, mu = 0)$p.value
return(1*(p2 < 0.05))
}
# Define upper_p thresholds to test
upper_ps <- c(.05, 0.25, 0.5, 0.75, 1.0)
n_sim <- 50000 # adjust for speed/precision
# Compute false-positive rate for each upper_p
fp_rates <- sapply(upper_ps, function(up) {
mean(replicate(n_sim, double.sample(upper_p = up)))
})
# Plot
plot(upper_ps, fp_rates, type = "b", pch = 19, col = "blue",
xlab = expression(Upper~p~threshold),
ylab = "False-positive rate",
main = "False-positive rate vs. upper p-value cutoffs")
abline(h = 0.05, col = "red", lty = 2) # baseline alpha
legend("topleft", legend = "alpha = 0.05", col = "red", lty = 2)What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
As I relaxed the decision criteria (aka doubled the sample for increasingly high p-value thresholds), the false-positive rate increased. This suggests that a data-dependent policy can fool researchers and readers into thinking an effect is more likely to exist even when it doesn’t. For example, using the above code, an upper p-value of .5 leads to a false-positive rate of about .08, while an upper p-value of 1 leads to a false-positive rate of about .084. I created a plot to show how the false-positive rate changes as a function of the upper p-value.