Intro

library(tidyverse)
## Loading tidyverse: ggplot2
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag():    dplyr, stats
library(ggthemes)
theme_set(theme_few())
sem <- function(x) {sd(x, na.rm=TRUE) / sqrt(sum(!is.na((x))))}
ci <- function(x) {sem(x) * 1.96} # reasonable approximation 

This is problem set #4, in which we hope you will practice the visualization package ggplot2, as well as hone your knowledge of the packages tidyr and dplyr. You’ll look at two different datasets here.

First, data on children’s looking at social targets from Frank, Vul, Saxe (2011, Infancy).

Second, data from Sklar et al. (2012) on the unconscious processing of arithmetic stimuli.

In both of these cases, the goal is to poke around the data and make some plots to reveal the structure of the dataset.

Part 1

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")
## Parsed with column specification:
## cols(
##   subid = col_integer(),
##   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.

#GRAPH ONE

#First spread data, and floor age

fvs.spread <- fvs %>%
  spread(condition, hand.look) %>%
  mutate(age = floor(age)) #need to floor age so can look by N = 1

#Create a plot with ages of two conditions -- regular histogram

ggplot(fvs.spread,
       aes(x = age)) + #you don't need a y variable is it's a histogram; fill shows separation
  geom_histogram(binwidth = 1, colour = "dark grey", fill="white") #want binwidth = 1, as this would be equal to 1 year 

#GRAPH TWO

#Other solution to plot conditions over each other
ggplot(fvs,
       aes(x = age,
           fill = condition)) + #you don't need a y variable is it's a histogram; fill shows separation
  geom_histogram(binwidth = 0.8, alpha= 0.5) + #alpha makes them transparent
  xlim(c(0,30))

Second, make a scatter plot showing the difference in hand looking by age and condition. Add appropriate smoothing lines. Take the time to fix the axis labels and make the plot look nice.

#Change labels in data set

fvs$condition <- as.factor(fvs$condition)

levels(fvs$condition) <- c("Less Complex Background","More Complex Background")
  

#Plot scatterplot

ggplot(fvs,
       aes(x = age,
           y = hand.look,
           col = condition))+
  geom_point() +
  geom_smooth(method = "lm",alpha=0.5, size = 1) +
  ylab("Hand Looking Amount") +
  xlab("Age (months)") +
  ggthemes::theme_few()

What do you conclude from this pattern of data?

From this data, you can conclude that for both conditions (e..g less & more complex backgrounds), the older children look at hands more. In addition, there is an interaction, such that older children the in the more complex background compared to older children the less complex one look at hands more.

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

I would conduct a linear regression with hand look amount as the dependent variable, and the age, condition, and their interaction as independent variables. My prediction is that there would be a main effect of age and a significant interaction between condition and age, but no main effect of condition.

Part 2

Sklar et al. (2012) claim evidence for unconscious arithmetic processing - they prime participants with arithmetic problems and claim that the authors are faster to repeat the answers. We’re going to do a reanalysis of their Experiment 6, which is the primary piece of evidence for that claim. The dataare generously shared by Asael Sklar. (You may recall these data from the tidyverse tutorial earlier in the quarter).

Data Prep

First read in two data files and subject info. A and B refer to different trial order counterbalances.

subinfo <- read_csv("data/sklar_expt6_subinfo_corrected.csv")
## Parsed with column specification:
## cols(
##   subid = col_integer(),
##   presentation.time = col_integer(),
##   subjective.test = col_integer(),
##   objective.test = col_double()
## )
d_a <- read_csv("data/sklar_expt6a_corrected.csv")
## Parsed with column specification:
## cols(
##   .default = col_integer(),
##   prime = col_character(),
##   congruent = col_character(),
##   operand = col_character()
## )
## See spec(...) for full column specifications.
d_b <- read_csv("data/sklar_expt6b_corrected.csv")
## Parsed with column specification:
## cols(
##   .default = col_integer(),
##   prime = col_character(),
##   congruent = col_character(),
##   operand = col_character()
## )
## See spec(...) for full column specifications.

gather these datasets into long (“tidy data”) form. If you need to review tidying, here’s the link to R4DS (bookmark it!). Remember that you can use select_helpers to help in your gathering.

Once you’ve tidied, bind all the data together. Check out bind_rows.

The resulting tidy dataset should look like this:

    prime prime.result target congruent operand distance counterbalance subid    rt
    <chr>        <int>  <int>     <chr>   <chr>    <int>          <int> <dbl> <int>
 1 =1+2+5            8      9        no       A       -1              1     1   597
 2 =1+3+5            9     11        no       A       -2              1     1   699
 3 =1+4+3            8     12        no       A       -4              1     1   700
 4 =1+6+3           10     12        no       A       -2              1     1   628
 5 =1+9+2           12     11        no       A        1              1     1   768
 6 =1+9+3           13     12        no       A        1              1     1   595
#Gather datasets for both

d_a_tidy <- d_a %>%
  gather(subid, rt, num_range('',1:21)) #need to specify that there is no prefix ... or could have said "1":"21"

d_b_tidy <- d_b %>%
  gather(subid, rt, num_range('',22:42)) #need to specify that there is no prefix
  
#Bind data sets 

d_tidy <- bind_rows(d_a_tidy,d_b_tidy) #bind rows as adding them

head(d_tidy)
## # A tibble: 6 x 9
##    prime prime.result target congruent operand distance counterbalance
##    <chr>        <int>  <int>     <chr>   <chr>    <int>          <int>
## 1 =1+2+5            8      9        no       A       -1              1
## 2 =1+3+5            9     11        no       A       -2              1
## 3 =1+4+3            8     12        no       A       -4              1
## 4 =1+6+3           10     12        no       A       -2              1
## 5 =1+9+2           12     11        no       A        1              1
## 6 =1+9+3           13     12        no       A        1              1
## # ... with 2 more variables: subid <chr>, rt <int>

Merge these with subject info. You will need to look into merge and its relatives, left_ and right_join. Call this dataframe d, by convention.

d_tidy$subid <- as.numeric(d_tidy$subid)

d <- right_join(subinfo,d_tidy)  #this returns all rows in d_tidy ("y"), and all columns across both
## Joining, by = "subid"
head(d)
## # A tibble: 6 x 12
##   subid presentation.time subjective.test objective.test  prime
##   <dbl>             <int>           <int>          <dbl>  <chr>
## 1     1              1700               0      0.5873016 =1+2+5
## 2     1              1700               0      0.5873016 =1+3+5
## 3     1              1700               0      0.5873016 =1+4+3
## 4     1              1700               0      0.5873016 =1+6+3
## 5     1              1700               0      0.5873016 =1+9+2
## 6     1              1700               0      0.5873016 =1+9+3
## # ... with 7 more variables: prime.result <int>, target <int>,
## #   congruent <chr>, operand <chr>, distance <int>, counterbalance <int>,
## #   rt <int>

Clean up the factor structure (just to make life easier). No need to, but if you want, you can make this more tidyverse-ish.

#Make presentation time a factor and then convert time to low & high

d$presentation.time <- factor(d$presentation.time)


#Turn Operand into the right levels

d$operand <- factor(d$operand)
levels(d$operand) <- c("addition","subtraction")

Data Analysis Preliminaries

Examine the basic properties of the dataset. First, show a histogram of reaction times.

ggplot(data=subset(d, !is.na(rt)),
       aes(rt))+
  geom_bar(stat = "bin", binwidth = 30, colour = "black", fill = "grey") + #this clusters so can see; adjust bin width for granularity
  xlab("Reaction Time (milliseconds)")
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.

Challenge question: what is the sample rate of the input device they are using to gather RTs?

The sample rate is every ~8 milliseconds. I found this by adjusting the bin width of reaction time until there were “gaps” between the bars, gaps which I assume was due to how the device collected data (and not due to participant actual reaction time). I wanted to find the maximum bin width until the gaps disappeared (as obviously very small bin widths would lead to large gaps). This was ~ 8 milliseconds.

Sklar et al. did two manipulation checks. Subjective - asking participants whether they saw the primes - and objective - asking them to report the parity of the primes (even or odd) to find out if they could actually read the primes when they tried. Examine both the unconscious and conscious manipulation checks. What do you see? Are they related to one another?

#Subjective manipulation check / Unconscious manpiulation check

ggplot(d,
       aes(x=subjective.test)) +
  geom_bar(stat="identity", binwidth = 0.1)
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.

#Objective test -- cluster based on if value is less than chance

ggplot(d,
       aes(x=objective.test)) +
  geom_density(bins = 50)
## Warning: Ignoring unknown parameters: bins

#Compare

d_subj_pass <- d[d$subjective.test==0,]
d_subj_fail <- d[d$subjective.test==1,]


ggplot(d_subj_pass,
       aes(x=objective.test)) +
  geom_histogram()+
  xlim(c(0,1))+
  ggtitle("Passed Subjective Test (=0)")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(d_subj_fail,
       aes(x=objective.test)) +
  geom_histogram()+
  xlim(c(0,1))+
   ggtitle("Failed Subjective Test (=1)")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

For the subjective test, around half passed (e.g. did not see the prime, subjective test = 0) and the other half failed (e.g. saw prime, subjective test = 1). For the objective test, there was a bimodal distribution such that many “passed” the objective test by scoring less than 0.6 (a bit greater than chance), and many others were much higher than chance. Are they related? When participants pass the subjective test, many seem to be passing the objective test as many had an objective test score of around 0.5; when participants fail the subjective test, many are above chance for the objective test.

Moreover, in the objective test, there is a binominal distribution, such that

In Experiments 6, 7, and 9, we used the binomial distribution to determine whether each participant performed better than chance on the objective block and excluded from analyses all those participants who did (21, 30, and 7 participants in Experiments 6, 7, and 9, respectively). Note that, although the number of excluded participants may seem high, they fall within the normal range of long-duration CFS priming, in which suc- cessful suppression is strongly affected by individual differences (38). We additionally excluded participants who reported any subjective awareness of the primes (four, five, and three participants in Experiments 6, 7, and 9, respectively).

OK, let’s turn back to the measure and implement Sklar et al.’s exclusion criterion. You need to have said you couldn’t see (subjective test) and also be not significantly above chance on the objective test (< .6 correct). Call your new data frame ds.

Include people who couldn’t see subjective prime (=0 on subjective test) and who were not above chance (<0.6 on ojbective test)

ds <- d %>%
  group_by(subjective.test,objective.test) %>%
  mutate(keep = ((subjective.test == 0) & (objective.test < 0.6))) %>% #subjective.test = 0 means didn't see the prime
  filter(keep)
 
ds
## # A tibble: 2,618 x 13
## # Groups:   subjective.test, objective.test [14]
##    subid presentation.time subjective.test objective.test  prime
##    <dbl>            <fctr>           <int>          <dbl>  <chr>
##  1     1              1700               0      0.5873016 =1+2+5
##  2     1              1700               0      0.5873016 =1+3+5
##  3     1              1700               0      0.5873016 =1+4+3
##  4     1              1700               0      0.5873016 =1+6+3
##  5     1              1700               0      0.5873016 =1+9+2
##  6     1              1700               0      0.5873016 =1+9+3
##  7     1              1700               0      0.5873016 =2+1+9
##  8     1              1700               0      0.5873016 =2+3+6
##  9     1              1700               0      0.5873016 =2+3+7
## 10     1              1700               0      0.5873016 =2+5+6
## # ... with 2,608 more rows, and 8 more variables: prime.result <int>,
## #   target <int>, congruent <chr>, operand <fctr>, distance <int>,
## #   counterbalance <int>, rt <int>, keep <lgl>

Replicating Sklar et al.’s analysis

Sklar et al. show a plot of a “facilitation effect” - the amount faster you are for prime-congruent naming compared with prime-incongruent naming. They then show plot this difference score for the subtraction condition and for the two prime times they tested. Try to reproduce this analysis.

HINT: first take averages within subjects, then compute your error bars across participants, using the ci function (defined above). Sklar et al. use SEM (and do it incorectly, actually), but CI is more useful for “inference by eye” as discussed in class.

HINT 2: remember that in class, we reviewed the common need to group_by and summarise twice, the first time to get means for each subject, the second time to compute statistics across subjects.

HINT 3: The final summary dataset should have 4 rows and 5 columns (2 columns for the two conditions and 3 columns for the outcome: reaction time, ci, and n).

ds$rt <- as.numeric(ds$rt)

ds.summary <- ds %>%
  group_by(subid, operand, presentation.time,congruent) %>%
  summarise(meansubjectrt = mean(rt, na.rm = TRUE)) %>%
  spread(congruent, meansubjectrt) %>% #Need to spread so can do a substraction
  mutate(facilitationeffect = no-yes) %>% #"(average RT in the priming condition) − (average RT in the control condition)"
  group_by(operand, presentation.time) %>%
  summarise(meanfacileff = mean(facilitationeffect),
            ci = ci(facilitationeffect),
            n = n())

Now plot this summary, giving more or less the bar plot that Sklar et al. gave (though I would keep operation as a variable here. Make sure you get some error bars on there (e.g. geom_errorbar or geom_linerange).

ggplot(ds.summary,
       aes (x = presentation.time,
            y = meanfacileff,
            fill = operand)) +
  geom_bar(stat="identity") +
  facet_wrap(~operand) +  
  geom_errorbar(aes(ymin = meanfacileff - ci, ymax = meanfacileff + ci),
                width = 0.1)+
  xlab("Presentation duration")+
  ylab("Facilitation (ms)")

What do you see here? How close is it to what Sklar et al. report? How do you interpret these data?

In this data, in the subtraction condition, there was a facilitation effect (reaction time in priming, when prime result and target were not congruent, minus reaction time in control condition, when prime result and target were congruent) for both presentation durations (1700 and 2000 ms) as the 95% confidence intervals did not cross 0. In addition, since the 95% confidence intervals for the two presentation durations overlapped, there was no interaction by presentation duration. However, for the addition condition, there was no facilitation effect for either presentation duration. This is the same result as what was found in the Sklar paper: ‘In the subtraction condition, reaction times (RTs) to correct responses showed a significant effect of priming (F1,15 = 16.79, P = 0.001) (Fig. 2A) and no interaction of priming and the prime presentation duration (P > 0.16).‡’

The only difference betwen my analysis and Sklar’s analysis is that in the subtraction 2000 presentation duration condition, the 95% confidence interval nearly goes through 0, meaning the effect seems to be weak.