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(tidyverse)
fvs <- read_csv("data/FVS2011-hands.csv")
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 %>% group_by(subid) %>% summarise(sub.age = mean(age)) %>%
ggplot() + geom_histogram(aes(x=sub.age), bins = 20) + ggthemes::theme_tufte() + ggtitle("Distribution of Ages of Subjects") + xlab("Subject Ages (months)") + ylab("Count")
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.
fvs %>% ggplot(aes(x=age, y=hand.look, color=condition)) +
geom_point() + geom_smooth(method = lm, formula = y ~ splines::ns(x, 3)) +
labs(title = "Hand-looking vs Age by Condition", x="Subject Age (months)", y="Hand-looking") +
ggthemes::theme_tufte()
What do you conclude from this pattern of data?
After about 10 months old, the condition appears to contribute more to the variance in the observations. The error variance of
Faces_Plusappears to be heteroskedastic. This is possibly because, the subjects that are older than 20 months are so few and are influential on the smoothed curve.It looks like the distribution ofHand-lookingperhaps closer to a gamma distribution than a normal.
What statistical analyses would you perform here to quantify these differences?
I would want to perform a multiple regression using age and condition as predictor variables, perhaps including
subidas a random effect, to account for individual child differences.
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(42)
replics = 10000
t.test.p.vals = data_frame("p.vals" = rep(NA,replics))
## Warning: `data_frame()` was deprecated in tibble 1.1.0.
## Please use `tibble()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
for (i in 1:replics){
t.test.p.vals[i,"p.vals"] = t.test(rnorm(30))$p.value
}
t.test.p.vals %>% filter(p.vals < 0.05) %>% count() / t.test.p.vals %>% count()
## n
## 1 0.0487
Next, do this using the replicate function:
t.test.p.vals = data.frame("p.vals" = replicate(10000,t.test(rnorm(30))$p.value))
t.test.p.vals %>% filter(p.vals < 0.05) %>% count() / t.test.p.vals %>% count() #]) #/length(t.test.p.vals)
## n
## 1 0.0498
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
The simulated false-positive rate are close to the expected false-positive rate for these samples.
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.
## This incorrect function was assuming that the scientist would keep doubling at 30, 60, 120,
## etc. for as long as the values weren't statistically significant.
## The correct function is below
# double.sample <- function (cutoff = 0.25, sample = 30) {
# subj = rnorm(sample)
# p = t.test(subj)$p.value
# while(p >= 0.05 & p <= cutoff){
# subj = c(subj,rnorm(length(subj)))
# p = t.test(subj)$p.value}
# return(c( p, length(subj)))}
double.sample <- function (cutoff = 0.25, sample.size = 30) {
subj = rnorm(sample.size)
p = t.test(subj)$p.value
if(p >= 0.05 & p <= cutoff){
subj = c(subj,rnorm(sample.size))
p = t.test(subj)$p.value
}
return(c( p, length(subj)))
}
Now call this function 10k times and find out what happens.
cutoff = 0.25
p.sniffing = data.frame(t(replicate(10000,double.sample(cutoff)))) %>% rename( "p.vals" = "X1", "n" = "X2")
p.snif.pct = p.sniffing %>% filter(p.vals < 0.05) %>% count() / p.sniffing %>% count()
p.snif.pct
## n
## 1 0.0701
Is there an inflation of false positives? How bad is it?
We increased the rate of false positives by about 50%.
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.
## Create a df for p values of 10000 runs
p.df = data.frame("iteration" = 1:10000)
for(cutoff in c(0.25,0.5,0.75,1)){
## for each of our cutoffs, add columns of p-values and sample size
new_name <- function(x){return(paste0(x,"-",cutoff))}
p.df = p.df %>% add_column(data.frame(t(replicate(10000,double.sample(cutoff)))) %>%
rename(p = "X1", n = "X2") %>% rename_with(new_name))
}
## Put data in tidy format
p.df = p.df %>% gather(names(p.df)[-1],key = "metric-run", value = "value") %>% separate("metric-run",sep = "-", into = c("metric","run"))
## Summarize to find the percentages
run.summary = p.df %>% group_by(run) %>% summarise(pct.signif = sum(if_else((metric =="p") & (value < 0.05),1,0))/n()*2,
pct.doubled = sum(if_else((metric =="n") & (value > 30),1,0))/n()*2)
## Create a plot of the summary
runplot <- run.summary %>% ggplot(aes(x=run,group=1)) +
geom_bar(aes(x=run,y=pct.signif), stat = "identity") +
geom_line(aes(x=run,y=pct.doubled/10),stat = "identity") +
labs(title = "% of Runs Stat. Significant or Doubled by Level of \'Optimism\'", x = "Optimism Cutoff",y = "% Stat. Significant (bar)") +
scale_y_continuous(sec.axis = sec_axis(~.*10, name = "% Samples Doubled (line)",labels = scales::percent), labels = scales::percent) +
ggthemes::theme_tufte()
run.summary
## # A tibble: 4 × 3
## run pct.signif pct.doubled
## <chr> <dbl> <dbl>
## 1 0.25 0.0703 0.200
## 2 0.5 0.0748 0.448
## 3 0.75 0.0822 0.705
## 4 1 0.0836 0.949
runplot
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
In the case where we know that there is no difference from the norm, we can double the likelihood of our statistical significance. So if we have an experiment where we have just a tiny bit of noise in our favor, we can double our chances of seeing a statistically significant result by resampling when we didn’t see one. That’s problematic. More data typically helps, but not when it is being filtered by statistical significance.