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)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1
## ✔ readr 2.1.2 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(tidyr)
library(dplyr)
library(stringr)
library(ggplot2)
library(lme4)
## Loading required package: Matrix
##
## Attaching package: 'Matrix'
##
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
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_unique <- fvs[!duplicated(fvs[,c('subid')]),]
#dim(fvs)
#dim(fvs_unique)
ggplot(fvs_unique, aes( x= age)) +
geom_histogram(binwidth = 0.8)
#ggplot(fvs, aes(x = age)) +
# geom_bar(width = .7)
#scale_x_discrete(labels = c("10", "15", "18", "20", "25"))
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()+
scale_x_continuous("Age")+
scale_y_continuous("looking time to hands")+
theme_minimal()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
What do you conclude from this pattern of data?
That the age and condition are not good predictors of the looking time to hands.
What statistical analyses would you perform here to quantify these differences?
I would use a t-test to quantify the difference in means between the two conditions.
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.
numberofsig = 0
set.seed(1)
for (counter in 1:10000) {
sample <- rnorm(30)
x = t.test(sample, mu=0, alternative = "two.sided")
if (x$p.value < 0.05)
{
numberofsig = numberofsig + 1
}
}
paste("number of significant results out of 10000 is", numberofsig )
## [1] "number of significant results out of 10000 is 502"
Next, do this using the replicate function:
numberofsig = 0
myfunc <- function()
{
sample <- rnorm(30)
x = t.test(sample, mu=0, alternative = "two.sided")
if (x$p.value < 0.05)
{
numberofsig = 1
}
return(numberofsig)
}
set.seed(1)
vectorofP = replicate(n=10000, myfunc() )
paste("number of significant results out of 10000 is", sum(vectorofP) )
## [1] "number of significant results out of 10000 is 502"
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
the false positive ratio in my simulation is 502/10000 which is 0.0502 .
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(3)
double.sample <- function () {
sample = rnorm(30)
df<-data.frame(sample)
colnames(df) <- c("newsample")
Pvalue = t.test(df, mu=0, alternative = "two.sided", var.equal = TRUE)$p.value
if (Pvalue < 0.25 & Pvalue >0.05 )
{
df2<-data.frame(newsample= rnorm(30))
df <- rbind(df,df2)
# df[nrow(df) + 30,] = newsample
}
# return(paste("the P-Value is", Pvalue))
return(Pvalue)
}
Now call this function 10k times and find out what happens.
vectorofP2 = replicate(n=10000, double.sample())
paste("Maximum Pvalue is", max(vectorofP2), "minimum Pvalue is", min(vectorofP2), "AND Number of significant results is", sum(abs(vectorofP2) < 0.05))
## [1] "Maximum Pvalue is 0.999936277700896 minimum Pvalue is 3.42293706815861e-05 AND Number of significant results is 486"
Is there an inflation of false positives? How bad is it?
The Pvalue went from 0.999 to 0.000005, so there is an inflation in the false positive rate and it is quite bad.
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.sample1 <- function (Pvalue) {
sample = rnorm(30)
df<-data.frame(sample)
colnames(df) <- c("newsample")
Pvalue = t.test(df, mu=0, alternative = "two.sided", var.equal = TRUE)$p.value
if (Pvalue < 0.5 & Pvalue >0.05 )
{
df2<-data.frame(newsample= rnorm(30))
df <- rbind(df,df2)
}
if (Pvalue < 0.75 & Pvalue >0.05 )
{
df2<-data.frame(newsample= rnorm(30))
df <- rbind(df,df2)
}
if (Pvalue >0.05 )
{
df2<-data.frame(newsample= rnorm(30))
df <- rbind(df,df2)
}
return(Pvalue)
}
set.seed(3)
vectorofP3 = replicate(n=10000, double.sample1())
paste("Maximum Pvalue is", max(vectorofP3), "minimum Pvalue is", min(vectorofP3), "AND Number of significant results is", sum(abs(vectorofP3) < 0.05))
## [1] "Maximum Pvalue is 0.999998169849439 minimum Pvalue is 1.67402573395375e-05 AND Number of significant results is 545"
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
I now see why a preregistration is important, modifying sample size after analyzing the data renders unreliable results obviously.