Psych 251 PS4: Visualization & Simulation

Author

Vivian Huynh

Published

December 31, 2022

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).

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ 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

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).

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.

children = subset(fvs, age < 18)

children
# A tibble: 204 × 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
 7    67  6.54 Faces_Medium    0.0242
 8    73  6.64 Faces_Medium    0.0669
 9    69  6.90 Faces_Medium    0.0314
10    84  7.23 Faces_Medium    0.105 
# ℹ 194 more rows
fvs |> group_by(subid)
# A tibble: 232 × 4
# Groups:   subid [119]
   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
 7    67  6.54 Faces_Medium    0.0242
 8    73  6.64 Faces_Medium    0.0669
 9    69  6.90 Faces_Medium    0.0314
10    84  7.23 Faces_Medium    0.105 
# ℹ 222 more rows
ggplot(children, aes(x = age)) +
  geom_histogram(binwidth = 1)

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(children, aes(x = age, y = hand.look, colour = condition)) +
  geom_point(alpha = .5) +
  geom_point(size=2, shape=21) +
  geom_smooth(method = "lm", se = TRUE) +
  ggtitle("Hand Looking by Children of Two Conditions") +
  xlab("Age of Children (months)") + 
  ylab("Hand Looking Time (sec)")
`geom_smooth()` using formula = 'y ~ x'

What do you conclude from this pattern of data?

I can conclude that the hand looking time of children in the Faces Medium condition is relatively shorter of those in the Faces plus condition. In the Faces Plus condition, children tended to look slightly longer at hands compared to the Faces Medium condition.

What statistical analyses would you perform here to quantify these differences?

To quantify these differences, we could perform a multiple linear regression to see the effect of hand looking time and age with two different conditions (Faces Medium and Faces Plus).

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.

simulations <- 10000
sample <- 30

data_results <- numeric(simulations)

# Create for loop that loops through simulations
for (i in 1: simulations)
{
  data <- rnorm(sample, 0, 1)
  t_test <- t.test(data)
  data_results[i] <- t_test$p.value < .05
}

significance <- mean(data_results)

significance
[1] 0.05

Next, do this using the replicate function:

# n represents num of times you want to replicate
data_replication <- replicate(10000, { data <- rnorm(30, 0, 1)
t_test_rep <- t.test(data)
t_test_rep$p.value < .05 })

significance_rep <- mean(data_replication)

significance_rep
[1] 0.054

How does this compare to the intended false-positive rate of \(\alpha=0.05\)?

The results were pretty similiar to each other!

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.

double.sample <- function() {
  data <- rnorm(30, 0, 1)
  t_test <- t.test(data)
  p <- t_test$p.value

  if (p < upper & p > lower) {
    rerun <- rnorm(30, 0, 1)
    new_data <- c(data, rerun)
    new_t <- t.test(new_data)
    new_p <- new_t$p
    return(new_p)
  }
    # for optimistic trials 
    if (p < upper) {
    rerun <- rnorm(30, 0, 1)
    new_data <- c(data, rerun)
    new_t <- t.test(new_data)
    new_p <- new_t$p
    return(new_p)
    } else {
    return(p)
  }
}

Now call this function 10k times and find out what happens.

upper <- .25
lower <- .05
results <- replicate(10000, double.sample()) 
final_res <- as.numeric(unlist(results)) # convert list to numeric
false_result <- mean(final_res)

false_result
[1] 0.6255291

Is there an inflation of false positives? How bad is it?

Yes, there is an inflation of false positives. It increases from the original .05 to .062 and changes as I continue to rerun the code block. The highest result I got was .064

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.

upper <- .5
results <- replicate(10000, double.sample())
final_res <- as.numeric(unlist(results)) # convert list to numeric
false_result <- mean(final_res)

false_result
[1] 0.7513956
upper <- .75
results <- replicate(10000, double.sample())
final_res <- as.numeric(unlist(results)) # convert list to numeric
false_result <- mean(final_res)

false_result
[1] 0.8739031
upper <- 1
results <- replicate(10000, double.sample())
final_res <- as.numeric(unlist(results)) # convert list to numeric
false_result <- mean(final_res)

false_result
[1] NaN

What do you conclude on the basis of this simulation? How bad is this kind of data-dependent policy?

The false positive results seem to slightly increase (but varies every time I rerun the code block) as we increase the threshold. I think this data-dependent policy is pretty bad because it is unreliable and doesn’t consistently change.