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).
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).
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(readr)
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.
head(fvs)
## # A tibble: 6 × 4
## subid age condition hand.look
## <dbl> <dbl> <chr> <dbl>
## 1 2 3.16 Faces_Medium 0.0319
## 2 93 5.03 Faces_Medium 0.119
## 3 29 5.85 Faces_Medium 0.0921
## 4 76 5.85 Faces_Medium 0.130
## 5 48 6.08 Faces_Medium 0.0138
## 6 101 6.15 Faces_Medium 0.0438
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)
ggplot(fvs, aes(x=age)) +
geom_histogram(binwidth = 1, fill="gray", color="black") +
xlab("Age (months)") +
ylab("Number of participants") +
ggtitle("Histogram of Ages of Children in the Study")
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(size = 1, shape = 3) +
xlab("Age (months)") +
ylab("Hand Looking Duration") +
ggtitle("Hand Looking as a Function of Age and Condition") +
geom_smooth(method = "loess", se = FALSE) +
theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'
What do you conclude from this pattern of data?
Based on the scatter plot and smoothing lines provided, it appears that there is a different trend in infant’s duration of hand looking as a function of a age and condition (i.e., faces_medium and faces_plus). In terms of age, there seems to be a non-linear relationship between age and hand looking duration.When it comes to condition, we can find the different patterns between conditions and age. For the
Faces_Pluscondition, the duration of hand looking for infants appears to decrease until around 10 months of age, then increases up to 20 months. However, after reaching 20 months, the hand looking duration begins to decrease again. Additionally, as the number of months increases, the distribution of the scatter plot points also becomes wider. In the case of theFaces_Mediumcondition, compared to theFaces_Pluscondition, there is a somewhat linear increase in hand looking duration as the age in months of the infants increases.
What statistical analyses would you perform here to quantify these differences?
To analyze the significant differences between two conditions (i.e., faces_medium and faces_plus), un-paired t-test is required. Moreover, the spread of the data points suggests there could be other factors influencing hand looking duration that are not accounted for by age and condition alone.Therefore, to quantify the observed differences and address the variability seen in the scatter plot, a mixed-effects regression model would be suitable due to the repeated measures design. For example, by including control variables (e.g., the sex of the infants), we could qunatify the differences of the hand looking duration depending on the condition and the age more explicitly.
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.
n <- 10000
significant_count <- 0
for (i in 1:n) {
sample_data <- rnorm(30, mean = 0, sd = 1)
test_result <- t.test(sample_data)
if (test_result$p.value < 0.05) {
significant_count <- significant_count + 1
}
}
proportion_significant <- significant_count / n
proportion_significant
## [1] 0.0524
Next, do this using the replicate function:
n <- 10000
p_values <- replicate(n, {
sample_data <- rnorm(30, mean = 0, sd = 1)
test_result <- t.test(sample_data)
test_result$p.value
})
proportion_significant <- mean(p_values < 0.05)
proportion_significant
## [1] 0.0501
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
Both of these results are very close to the intended false-positive rate of 0.05. Both of these results are very close to the intended false-positive rate of 0.05. This means that when running a t-test where the null hypothesis is actually true (as it is in this simulation where the data comes from a distribution with mean 0), there is a posiblity to incorrectly reject the null hypothesis (conclude that there is a significant effect) about 5% of the time. This is expected because the significance level (alpha) is set at 0.05, indicating a 5% risk of committing a Type I error (false positive).
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(1)
double.sample <- function() {
# 30 participants
initial_sample <- rnorm(30, mean = 0, sd = 1)
initial_test <- t.test(initial_sample)
if (initial_test$p.value < 0.05) {
result <- 'stop-significant'
final_p_value <- initial_test$p.value
} else if (initial_test$p.value > 0.25) {
result <- 'stop-not-significant'
final_p_value <- initial_test$p.value
} else {
additional_sample <- rnorm(30, mean = 0, sd = 1)
combined_sample <- c(initial_sample, additional_sample)
final_test <- t.test(combined_sample)
result <- 'continued'
final_p_value <- final_test$p.value
}
return(list(result = result, p_value = final_p_value))
}
double.sample()
## $result
## [1] "stop-not-significant"
##
## $p_value
## [1] 0.6287113
Now call this function 10k times and find out what happens.
# Simulation of 10,000 experiments
set.seed(123) # Setting a seed for reproducibility
simulation_results <- replicate(10000, double.sample(), simplify = FALSE)
# Analyzing the results
results_table <- table(sapply(simulation_results, `[[`, "result"))
# Proportion of each type of result
proportions <- results_table / sum(results_table)
# Print the proportions
proportions
##
## continued stop-not-significant stop-significant
## 0.2066 0.7463 0.0471
Is there an inflation of false positives? How bad is it?
the simulation of 10,000 experiments yielded: 62% of experiments were stopped without significance (stop-not-significant). 4.71% of experiments were stopped with a significant result (stop-significant). 20.66% of experiments continued to a second test (continued). The proportion of stopped experiments with a significant result is slightly lower than the nominal 5% alpha level. However, the continued category indicates additional tests were performed, which could potentially increase the overall false positive rate. To fully assess the inflation of false positives, I need to consider the outcomes of the second tests in the continued group.
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:
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(upper_threshold) {
initial_sample <- rnorm(30, mean = 0, sd = 1)
initial_test <- t.test(initial_sample)
if (initial_test$p.value < 0.05) {
result <- 'stop-significant'
final_p_value <- initial_test$p.value
} else if (initial_test$p.value > upper_threshold) {
result <- 'stop-not-significant'
final_p_value <- initial_test$p.value
} else {
additional_sample <- rnorm(30, mean = 0, sd = 1)
combined_sample <- c(initial_sample, additional_sample)
final_test <- t.test(combined_sample)
result <- 'continued'
final_p_value <- final_test$p.value
}
return(list(result = result, p_value = final_p_value))
}
run_simulation <- function(upper_threshold, n) {
simulation_results <- replicate(n, double.sample(upper_threshold), simplify = FALSE)
results_table <- table(sapply(simulation_results, `[[`, "result"))
proportions <- results_table / sum(results_table)
return(proportions)
}
# Run simulations for each scenario
p_thresholds <- c(0.5, 0.75, 1.0)
n_simulations <- 10000
results <- lapply(p_thresholds, function(p) run_simulation(p, n_simulations))
names(results) <- paste("Threshold", p_thresholds)
results
## $`Threshold 0.5`
##
## continued stop-not-significant stop-significant
## 0.4432 0.5043 0.0525
##
## $`Threshold 0.75`
##
## continued stop-not-significant stop-significant
## 0.6976 0.2517 0.0507
##
## $`Threshold 1`
##
## continued stop-significant
## 0.9522 0.0478
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
threshold of 0.5 : there’s a false positive rate of approximately 5.22%. This is slightly above the expected rate of 5%, suggesting a small but present inflation in the Type I error rate due to the more lenient threshold for continuing the experiment. threshold of 0.75 : the false positive rate remains at 5%. This suggests that even with a more optimistic threshold, the false positive rate does not inflate beyond the nominal alpha level in this simulation. threshold of 1 : effectively allowing for continuation regardless of the initial p-value unless it is significant, the continued rate is very high (95.07%), but the stop-significant rate is about 4%, which is slightly below the nominal rate.
It appears that allowing for more lenient thresholds for doubling the sample does not dramatically inflate the false positive rate in this specific scenario. However, it’s crucial to note that this kind of data-dependent policy can increase the risk of Type I errors in practice, particularly if the decision to continue collecting data is influenced by the desire for a significant result.