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).
# import packageslibrary(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
✔ ggplot2 3.5.2 ✔ tibble 3.2.1
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.0.2
── 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
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.
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() +geom_smooth(method ="lm") +theme_classic() +labs(title ="Hand Looking by Age and Study Condition", x ="Age (months)",y ="Hand Looking Time (seconds)",color ="Condition") +theme(plot.title =element_text(hjust =0.5))
`geom_smooth()` using formula = 'y ~ x'
What do you conclude from this pattern of data?
Older children look at hands for longer amounts of time than younger children, regardless of condition. Differences in time spent looking at one’s hand as a function of condition (Faces_Medium compared to Faces_Plus) increases with age.
What statistical analyses would you perform here to quantify these differences?
For the main effect of age on hand looking time, I would run a linear regression. To see if this is different between conditions, I would run a simple slope analysis.
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.
#different answers without set seed, so I used one here# mean 0, SD 1, 30 people, so rnorm(30,0,1)set.seed(123)count <-0# Run 10,000 t-testsfor (i in1:10000) { sim_data <-rnorm(30, 0, 1) t_test <-t.test(sim_data, mu =0) p_value <- t_test$p.valueif (p_value <0.05) { count <- count +1 }}print(count/10000) # proportion of "significant" results (p < .05)
set.seed(123)p_values <-replicate(10000, { sim_data <-rnorm(30, 0, 1) t_test <-t.test(sim_data, mu =0) t_test$p.value})mean(p_values <0.05) # proportion of "significant" results
[1] 0.0465
#alternative from stack overflow set.seed(123)p_values <-replicate(10000, t.test(rnorm(30))$p.value)mean(p_values <0.05)
[1] 0.0465
How does this compare to the intended false-positive rate of \(\alpha=0.05\)?
Setting the seed gave a consistent false positive rate (0.0465) but without a set seed the false-positive rate varied, however, it was always close to the false positive rate of 0.05.
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.
Is there an inflation of false positives? How bad is it?
If I’m understanding the idea of false positives, we should randomly have a false positive value of 0.05 (p>0.05 being used as a chance cutoff). Because the generated value was typically around .07 (sometimes .072, sometimes .0681), this is increasing the false positive rate by 2 percentage points. I think the values are not alarming, but not knowing if the study used a stopping rule to collect the data or kept recruiting after viewing the data means someone could continue to build on this and the false positive rate would be worse.
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.
#Disclosure of Claude use: Here, I copied the problem, the answer #I originally came up with, and the prompt to 'Create recommendations #for neater code, identify any incorrect patterns in thinking, or confirm #if the code is fine as is'. Claude identified that I originally simulated #continuous peeking instead of doubling the sample, and the cutoff was arbitrary. #The code below is what I worked through using Claude to get the conditional#aaspects of significance values correct. #Also, did the prompt mean double the sample once? #I read it as they keep doubling the sample, as long as the values #were between the numbers stated above. So it would have a different answer #if it was 'double each time you peak' vs double once after one initial result. #create a function for less than .05 double_sample <-function(p_upper, n =30) { first_data <-rnorm(n) p_value <-t.test(first_data)$p.valueif (p_value > .05& p_value < p_upper) { all_data <-c(first_data, rnorm(n)) p_value <-t.test(all_data)$p.value } p_value}#see what happens when the cutoffs above are implemented .05, .75, 1.00 is when any is not significant because it is more than .05 (defined above) and less than 1 N_SIMS <-10000results <-tibble(p_upper =c(.05, .25, .50, .75, 1.00)) |>mutate(false_positives =map_dbl(p_upper, \(p) mean(replicate(N_SIMS, double_sample(p)) < .05)),standard_error =sqrt(false_positives * (1- false_positives) / N_SIMS))print(results)
What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?
There are two interpretations of the question - both situations are bad, but one situation compounds the issue and is far worse. The two scenarios are ‘double your sample each time you peak’ vs double once after one initial result. The double after the initial peak raises the false positive rate, but raising it caps out at .08, which is well above .05, but not nearly as bad as the ‘double your sample based on your p-value each time, until significance’, which continually raised the false positive rate well into double digits. It suprises me that we often don’t know why someone stopped at a certain sample size, or if they checked the data before adding more people. I understand at some point science requires trust (ie, trusting all people were collected at once, if researchers needed to increase their n it isn’t because they peaked at the data first, etc) but I am glad for pre-registration to make that question more clear.