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
ggplot2practice.
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, andFaces_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).
#install.packages("knitr")
library("knitr") # for rendering the RMarkdown file
#install.packages(c("gganimate", "patchwork", "gapminder"))
library("gganimate") # for making animations
## Loading required package: ggplot2
## No renderer backend detected. gganimate will default to writing frames to separate files
## Consider installing:
## - the `gifski` package for gif output
## - the `av` package for video output
## and restarting the R session
library("patchwork") # for making figure panels
library("gapminder") # data available from Gapminder.org
library("tidyverse") # for plotting (and many more cool things we'll discover later)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble 3.0.4 ✓ dplyr 1.0.2
## ✓ tidyr 1.1.2 ✓ stringr 1.4.0
## ✓ readr 1.3.1 ✓ forcats 0.5.0
## ✓ purrr 0.3.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
#install.packages("rlist")
library(rlist)
fvs <- read_csv("data/FVS2011-hands.csv")
## Parsed with column specification:
## cols(
## subid = col_double(),
## age = col_double(),
## condition = col_character(),
## hand.look = col_double()
## )
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.
ggplot(data = fvs,
filter(condition == "Faces_Medium"),
mapping = aes(x = age)) +
geom_histogram(color = "black",
fill = "lightblue") +
coord_cartesian(xlim = c(3,28),
expand = F) +
facet_grid(cols = vars(condition)) +
labs(title = "Faces_Medium")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
ggplot(data = fvs,
filter(condition == "Faces_Plus"),
mapping = aes(x = age)) +
geom_histogram(color = "black",
fill = "lightblue") +
facet_grid(cols = vars(condition)) +
labs(title = "Faces_Plus")
## `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.
summary(fvs)
## subid age condition hand.look
## Min. : 1.00 Min. : 3.156 Length:232 Min. :0.00000
## 1st Qu.: 30.75 1st Qu.: 9.403 Class :character 1st Qu.:0.02677
## Median : 59.50 Median :11.868 Mode :character Median :0.06309
## Mean : 59.79 Mean :12.375 Mean :0.07150
## 3rd Qu.: 89.00 3rd Qu.:14.778 3rd Qu.:0.10507
## Max. :119.00 Max. :27.847 Max. :0.34560
ggplot(data = fvs,
mapping = aes(x = age,
y = hand.look,
color = condition)) +
geom_point() +
geom_smooth(method = "lm", se = T) +
labs(y = "count of hand looking") +
scale_x_continuous(breaks= 3:28, expand = expansion(add = c(2, 2))) +
scale_y_continuous(expand = expansion(add = c(0, 0.1)))
## `geom_smooth()` using formula 'y ~ x'
What do you conclude from this pattern of data?
After age 7, significantly more children look at hands when condition is “faces_medium”
What statistical analyses would you perform here to quantify these differences?
A t-test (or F test if we run a regression) to test the null hypothesis i.e. can the hypothesis that the mean of the two conditions comes from the same distribution be rejected. We can also calculate the Bayes factor to estimate the odds of the two distributions being the same against the distributions being different
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.
# define how many samples to draw
nsamples = 30
nttest=10000
mu0=0
alpha=0.05
result=c()
for (i in 1:nttest) {
x = tibble(random_numbers = rnorm(n = nsamples, mean = 0, sd = 1))
result[i]=(t.test(x, mu=0, alternative = "two.sided", conf.int = 0.95)$p.value)<alpha #Checking if mean is different from 0
}
#Calculate mean of ttests
mean(result)
## [1] 0.0523
Next, do this using the replicate function:
nsamples = 30
nttest=10000
mu0=0
alpha=0.05
p_values = replicate(n=nttest,
t.test(rnorm(nsamples),mu=0,conf.int = 0.95)$p.value<alpha)
mean(p_values)
## [1] 0.0515
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
the result is very close to the intended false positive rate
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.
# define how many samples to draw
nsamples=30
mu0=0
alpha=0.05
obs =c()
double.sample <- function () {
obs=rnorm(nsamples)
p_values = t.test(obs,mu=0,conf.int = 0.95)$p.value
is_significant=p_values<alpha
#check if we can return the value
if(p_values<0.05 | p_values>0.25) {
return(is_significant)
}
#run loop till condition for pvalue is met
while(p_values>0.05 && p_values<0.25) {
obs=list.append(obs,rnorm(nsamples))
p_values = t.test(obs,mu=0,conf.int = 0.95)$p.value
is_significant=p_values<alpha
if(p_values<0.05 | p_values>0.25) {
return(is_significant)
}
}
}
Now call this function 10k times and find out what happens.
ntrials=10000
sum(replicate(ntrials, double.sample()))
## [1] 823
Is there an inflation of false positives? How bad is it?
Yes, the rate of false positive increased, there is an inflation
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.
nsamples=30
mu0=0
alpha=0.05
obs =c()
double.sample <- function (upper) {
obs=rnorm(nsamples)
p_values = t.test(obs,mu=0,conf.int = 0.95)$p.value
is_significant=p_values<alpha
#check if we can return the value
if(p_values<0.05 | p_values>upper) {
return(is_significant)
}
#run loop till condition for pvalue is met
while(p_values>0.05 && p_values<upper) {
obs=list.append(obs,rnorm(nsamples))
p_values = t.test(obs,mu=0,conf.int = 0.95)$p.value
is_significant=p_values<alpha
if(p_values<0.05 | p_values>0.25) {
return(is_significant)
}
}
}
ntrials=10000
#Sample 1: upper limit of pvalue=0.5
upper= 0.5
sum(replicate(ntrials, double.sample(upper)))/ntrials
## [1] 0.105
# the probability of false negative is now 10%
#increase number of samples
# the probability of false negative is still 10%
(sum(replicate(ntrials*10, double.sample(upper))))/(ntrials*10)
## [1] 0.10554
#Sample 1: upper limit of pvalue=0.75
upper= 0.75
(sum(replicate(ntrials, double.sample(upper))))/ntrials
## [1] 0.1182
# the probability of false negative is now 12%
#increase number of samples
(sum(replicate(ntrials*10, double.sample(upper))))/(ntrials*10)
## [1] 0.11495
#Sample 1: any insignificant pvalue i.e. upper limit of pvalue=1
upper= 1
sum(replicate(ntrials, double.sample(upper)))/ntrials
## [1] 0.1187
# the probability of false negative is still 12%. Increasing sample size, probability is 12%
sum(replicate(ntrials*10, double.sample(upper)))/(ntrials*10)
## [1] 0.11979
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
p-hacking more than doubled the chances of false negative i.e. in 12 out of 100 cases, we would find the result to be significantly different from 0, even though we drew the sample from a normal distribution and the CI is 5%.