fvs <- read.csv("data/FVS2011-hands.csv")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).
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.
library(ggplot2)
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
✔ lubridate 1.9.4 ✔ tibble 3.2.1
✔ purrr 1.0.2 ✔ tidyr 1.3.1
── 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 %>%
group_by(subid) %>%
summarize(age = first(age)) %>% # help from GPT to account for repeated measures
ggplot(mapping = aes(x = age)) +
geom_histogram(alpha = 0.5,
binwidth = 3,
color = "black",
fill = "pink") +
labs(title = "Distribution of Children's Ages",
x = "Age in Months",
y = "Observations") +
theme_classic()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(data = fvs,
mapping = aes(x = age,
y = hand.look,
color = condition)) +
geom_point(alpha = 0.3) +
geom_smooth(method = "lm",
color = "purple",
aes(fill = condition),
alpha = 0.5) +
labs(title = "Hand Looking As a Function of Age & Condition",
x = "Age in Months",
y = "Hand Looking ") +
scale_x_continuous(limits = c(4, 28), breaks = seq(4, 28, by = 4)) +
theme_classic() `geom_smooth()` using formula = 'y ~ x'
Warning: Removed 2 rows containing non-finite outside the scale range
(`stat_smooth()`).
Warning: Removed 2 rows containing missing values or values outside the scale range
(`geom_point()`).
What do you conclude from this pattern of data?
Across the board, as children get older, hand looking increases, but this effect is more pronounced in the Faces Plus condition (i.e., when children watched the movie with the more complex, rather than just white, background).
What statistical analyses would you perform here to quantify these differences?
I would fit a linear model with hand looking as the outcome and age and condition as predictors.
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(123)
n_simulations = 10000
sample_size = 30
mean = 0
sd = 1
pvals = numeric(n_simulations)
for (i in seq_len(n_simulations)) {
sim_data <- rnorm(sample_size, mean = mean, sd = sd)
pvals[i] <- t.test(sim_data, mean = mean)$p.value
}
# GPT directed me to the "numeric" function, and the functions within "for"
prop_sig <- mean(pvals < 0.05)
prop_sig [1] 0.0465
Next, do this using the replicate function:
set.seed(123) #GPT
pvals = replicate(n_simulations, {
sim_data = rnorm(sample_size, mean = mean, sd = sd)
t.test(sim_data, mu = mean)$p.value # GPT explained the utility of using "mu" instead of "mean
})
prop_sig <- mean(pvals < 0.05)
prop_sig [1] 0.0465
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
Compared to the false-positive rate of alpha = .05, the false-positive rate found here is almost the same (the same when rounded up).
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(n1 = 30,
n2 = 30,
true_mean = 0,
true_sd = 1) {
sim_data_1 <- rnorm(n = n1, mean = true_mean, sd = true_sd)
p1 <- t.test(sim_data_1, mu = 0)$p.value
if (p1 < .05 || p1 > 0.25) { # GPT helped with code for returning the p value
return(list(
p_initial = p1,
p_final = p1,
n_final = n1,
continued = FALSE,
significant = p1 < .05
))
}
sim_data_2 <- rnorm(n = n2, mean = true_mean, sd = true_sd)
sim_data_all <- c(sim_data_1, sim_data_2)
p2 <- t.test(sim_data_all, mu = 0)$p.value
return(list(
p_initial = p1,
p_final = p2,
n_final = n1 + n2,
continued = TRUE,
significant = p2 < .05
))
}
set.seed(123)
double.sample()$p_initial
[1] 0.7944204
$p_final
[1] 0.7944204
$n_final
[1] 30
$continued
[1] FALSE
$significant
[1] FALSE
Now call this function 10k times and find out what happens.
set.seed(123)
pval <- replicate(n_simulations, double.sample())
mean(pval < .05)[1] 0.3681
Is there an inflation of false positives? How bad is it?
Yes, given that the false positive rate was .05, and now it is .067, the rate has been inflated.
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(n1 = 30,
n2 = 30,
true_mean = 0,
true_sd = 1,
sniff_upper = 0.25) {
sim_data_1 <- rnorm(n = n1, mean = true_mean, sd = true_sd)
p1 <- t.test(sim_data_1, mu = 0)$p.value
# GPT helped with this code to set the default to no continuation
continued <- FALSE
n_final <- n1
p_final <- p1
if (p1 >= 0.05 && p1 <= sniff_upper) {
sim_data_2 <- rnorm(n = n2, mean = true_mean, sd = true_sd)
sim_data_all <- c(sim_data_1, sim_data_2)
p_final <- t.test(sim_data_all, mu = 0)$p.value
continued <- TRUE
n_final <- n1 + n2
}
return(list(
p_initial = p1,
p_final = p_final,
n_final = n_final,
continued = continued,
significant = p_final < 0.05
))
}
set.seed(123)
n_simulations = 20000
data_samples <- tibble(sniff_upper = c(.25, .5, .75, 1)) %>% # 1 = "any non-significant p"
rowwise() %>% # apply each threshold to each row in the dataframe
mutate(
false_positive_rate = mean(
replicate(
n_simulations,
double.sample(sniff_upper = sniff_upper)$p_final < 0.05
)
)
) %>%
ungroup()
data_samples# A tibble: 4 × 2
sniff_upper false_positive_rate
<dbl> <dbl>
1 0.25 0.0704
2 0.5 0.0795
3 0.75 0.0810
4 1 0.0822
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
This simulation shows us that with this data-dependent policy, the false-positive rate (i.e., Type I error) steadily increases as the researcher “strategically” increases the sample size.