Practical Statistics Documentation

Author

Ray Tanzer

Published

January 18, 2024

Preface

Thank you for participating in Practical Statistics! This document is intended to provide additional documentation on the R code used throughout this course. Some background on the specific topics covered will be provided as context, but please refer to slideshows for full details. The first four topics will cover the basics of using R, big picture research conceptualization, probability theory, and hypothesis testing. Topics five through nine are the focus of this program, using different forms of regression analysis to test a specific hypothesis. The first four topics focus on hypothetical examples, but the applied regression analysis section will focus on a real world example of a randomized experimental trial comparing how practicing gratitude against a control condition may change the way people experience stress, psychologically and physiologically.

If you’ve taken a class on research methodology before, this program will be a little different. This program will not cover everything about writing code in R or every analytic approach you could use. Instead, the focus is on identifying a hypothesis to provide an answer to research question, and testing it in data. Substantive examples are formulated around the following:

  • Theory: The motivations for research and substantive topics the analysis seeks to provide an insight into
  • Scientific hypothesis: A conceptual expectation for similarities and differences between groups and traits compared within the analysis
  • Testable hypothesis: A numeric expectation for the specific values measures will demonstrate in statistics estimated from a sample of data
  • Null hypothesis: A preliminary assumption about the samples of data which the researcher hopes to rule out if there is sufficient evidence in the data (see Topic 4 on hypothesis testing)
  • Threat to validity: Limitations in the data collection and research design that need to be kept in mind while interpreting the results and formulating an analysis plan

The convenience of computer assisted analysis has enabled automatically output statistics, however it may not be immediately clear which statistics actually provide evidence that could facilitate a meaningful discussion of a scientific topic. By starting from broad conceptualization in theory, and adding layers of specificity to the research question and data collected in identifying scientific, testable, and null hypotheses, this approach will help to identify which statistics are actually relevant to the research question, and how to identify them in the data. Additionally, being aware of threats to validity provide an opportunity to fine tune the analysis to account for known limitations in the data while formulating the analysis plan.

In terms of analytic approaches, that is another difference between this program and conventional research methodology course curriculum. Where it is common to cover topics such as the t test, ANOVA, and chi square tests, this program will focus on performing analysis entirely via generalized linear regression modeling. The reason for formulating analysis in this way is these other analytic approaches can be recreated with mathematical equivalence within regression analysis, however there are some analytic advantages to regression analysis that can not be achieved within these other analytic approaches. Additionally, by focusing on one analytic approach that can be applied to most research situations, skills learned along the way build on each other. Rather than needing to memorize the unique conditions in which different approaches can be used or differing assumptions for each analytic approach, the same assumptions apply, and in many cases similar lines of code can be used to accomplish different tasks. This helps to keep the focus on identifying meaningful hypotheses that account for the real complexities of data collection, which is generally more difficult and essential to performing the mathematical calculations. After estimating regression models, a linear combination matrix (L matrix) can be used to estimate more intuitive descriptive statistics implied by the model results and generate interpretable plots of the results that can be tailored to the testable hypothesis. This can help to clarify results and ensure that the interpretation of the findings and reported statistics are consistent with the goals of research.

Lastly, a primary focus of this program is to make analysis intuitive especially by way of using pictures rather than numbers. In many cases, you have an idea of what conclusions can be drawn from a plot of data, the numbers just tell you whether or not observed features are sufficiently precise to call them statistically meaningful. By conceptualizing research starting with theory and performing analysis within regression, this can help identify and generate plots of the data would be insightful. With the code provided, every statistical test performed will generate a plot of the data that resulted in that statistical test, which helps ensure that reporting of data is consistent with the statistics that lead to a conclusion.

Ultimately, that’s the intention of this program. Success in science isn’t anything special, it isn’t mathemagic, it’s just a matter of thoughtful ideas and good organization. This program is intended to provide a guide for organizing your thoughts and connecting them to the data collelcted without having to oversimplify the complexity of the real world that is relevant to data collection. Thank you again for your participation, and if you need anything don’t hesitate to email or set up a meeting together!

Ray

jtanzer@lifespan.org

joshua_tanzer@brown.edu

Topic 1: Getting Started in R

Learning Goals

The focus of this first section is to overview some of the very basics using R software.

First, a couple of notes for using R:

  • Pound sign (#) is a comment and will not be read as code
  • R is case sensitive (i.e., “code” is different than “Code”)

Getting Started with Packages

R is crowdsourced, so anybody can write their own code and share with others. Code available to download in R is called a package. To install a package, run install.packages(“Package_Name”). You only need to do this once, after it is installed you can use the package as often as you like!

#(Only do once)
install.packages("psych")
install.packages("glmmTMB")
install.packages("survival")
install.packages("DataEditR")
install.packages("tidyverse")
install.packages("rhandsontable")
install.packages("ggplot2")
install.packages("EnvStats")
install.packages("cluster")
install.packages("plotly")

Every time you start R, you will need to load any packages you want to use. This can be accomplished using library(Package_Name)

#Do every time you start R
library(psych)
Warning: package 'psych' was built under R version 4.3.1
library(glmmTMB)
Warning: package 'glmmTMB' was built under R version 4.3.1
library(survival)
library(DataEditR)
library(tidyverse)
Warning: package 'purrr' was built under R version 4.3.1
Warning: package 'dplyr' was built under R version 4.3.1
-- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --
v dplyr     1.1.3     v readr     2.1.4
v forcats   1.0.0     v stringr   1.5.0
v ggplot2   3.4.2     v tibble    3.2.1
v lubridate 1.9.2     v tidyr     1.3.0
v purrr     1.0.2     
-- Conflicts ------------------------------------------ tidyverse_conflicts() --
x ggplot2::%+%()   masks psych::%+%()
x ggplot2::alpha() masks psych::alpha()
x dplyr::filter()  masks stats::filter()
x dplyr::lag()     masks stats::lag()
i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rhandsontable)
library(ggplot2)
library(EnvStats)
Warning: package 'EnvStats' was built under R version 4.3.1

Attaching package: 'EnvStats'

The following objects are masked from 'package:stats':

    predict, predict.lm
library(cluster)
library(plotly)
Warning: package 'plotly' was built under R version 4.3.1

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
library(MASS) #Already installed with base R
Warning: package 'MASS' was built under R version 4.3.1

Attaching package: 'MASS'

The following object is masked from 'package:plotly':

    select

The following object is masked from 'package:EnvStats':

    boxcox

The following object is masked from 'package:dplyr':

    select
library(readr) #Already installed with base R
library(readxl) #Already installed with base R
Warning: package 'readxl' was built under R version 4.3.1
library(haven) #Already installed with base R
Warning: package 'haven' was built under R version 4.3.1

To run code, simply select what you want to run and click “run” in the top right or type control+enter.

You can also write your own functions and read them in, like a package. The details of function writing is beyond what we will cover in this program, but I have written some functions that we will use. The code is freely available and can be directly loaded into R thanks to github. The following code will load all of the functions you need for this course.

source("https://raw.githubusercontent.com/JoshuaRayTanzer/Functions/main/Functions.R")
Warning: package 'shiny' was built under R version 4.3.1

A part of what makes this file convenient is that it automatically will run the library statements for all the packages it depends on. This makes coding simpler, rather than needing to remember all the packages you will need when you start a new project, this will automatically call all the basic packages for performing analysis these programs are designed to interface with so you don’t need to.

Loading and Manipulating Data

You can upload data from dropdowns, just go to:

File>Import Dataset

and then select the file format from the menu.

Using code, you can specify using the following

#For tab separated files
data=read.table("file/location/Data.txt",sep="\t",header=T)

#for CSV
data=read.csv("file/location/Data.csv")

#for Excel
data=read_excel("file/location/Data.xlsx")

#for SPSS
data=read_sav("file/location/Data.sav")

I find the simplest and easiest way to get data into R is to store data in an Excel file, and simply copy and paste it into a text file. You can then use the read.table function to read it in. I like this approach because it works without any packages (e.g., read_excel requires the readxl package, read_sav requires the haven package) and a text document doesn’t have any complexity (e.g., tabs in Excel). The simpler it can be, the less opportunity for problems!

You can also create data manually. The c() can be used to define a list vector of inputs (numbers or letters)

x1=c(1,2,3)
x2=c("a","b","c")

This is called an “object”. To view an object, select its name and run it

x1
[1] 1 2 3
x2
[1] "a" "b" "c"

Note that all objects can be found in the top right “Global Environment”.

For objects that represent a list or matrix, cbind can be used to combine them as columns, and rbind as rows

rows=rbind(x1,x2)
rows
   [,1] [,2] [,3]
x1 "1"  "2"  "3" 
x2 "a"  "b"  "c" 
cols=cbind(x1,x2)
cols
     x1  x2 
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"

These are currently defined as matrices, but they can be converted to a “data frame” format. The data frame stores data more flexibly in R, so some functions require that data be formatted as a data frame.

df=data.frame(cols)
df
  x1 x2
1  1  a
2  2  b
3  3  c

You can also change the column and row names of a data frame to help keep organized.

colnames(df)=c("Number","Letter")
row.names(df)=c("First","Second","Third")
df
       Number Letter
First       1      a
Second      2      b
Third       3      c

Mathematical Operations for Numeric Data

First and foremost, R is a basic calculator!

1+1
[1] 2
1-1
[1] 0
1*2
[1] 2
1/2
[1] 0.5
2^2
[1] 4
sqrt(4)
[1] 2
log(16) #assumes natural log
[1] 2.772589
log(16,base=2)
[1] 4
exp(0.5)
[1] 1.648721

Conveniently, you can use objects to streamline the process

a=2
b=3

a+b
[1] 5
a*b
[1] 6
b^a
[1] 9

This is more valuable when we use more complex procedures to perform analysis. The output from one function can be defined as an object, and post processing of that output can be performed in a much more streamlined process as additional mathematical or graphical functions can be applied.

We can also do matrix operations on data frames and matrix objects!

x1=c(1,2,3)
x2=c(4,5,6)
x=rbind(x1,x2)
x
   [,1] [,2] [,3]
x1    1    2    3
x2    4    5    6

To count up the dimension of objects, we can do length() to identify the number of inputs in a vectors

length(x1)
[1] 3

and for matrices and dataframes we can use dim() and nrow() and ncol() to extract the dimensions

dim(x)
[1] 2 3
nrow(x)
[1] 2
ncol(x)
[1] 3

We can also do sums, products, and averages across the matrix

sum(x)
[1] 21
prod(x)
[1] 720

or we can also pick out one specific row to focus on using matrix notation

#Matrix notation is defined as:
#matrix[row number,column number]

#Identifying the first column
x[,1]
x1 x2 
 1  4 
sum(x[,1])
[1] 5
#Identifying the first row
x[1,]
[1] 1 2 3
sum(x[1,])
[1] 6

or by specifying the name if it is a data frame using a dollar sign ($)

x_df=data.frame(x)
colnames(x_df)=c("x1","x2","x3")
x_df$x1
[1] 1 4
sum(x_df$x1)
[1] 5

The transpose can be performed as t()

x_t=t(x)
x
   [,1] [,2] [,3]
x1    1    2    3
x2    4    5    6
x_t
     x1 x2
[1,]  1  4
[2,]  2  5
[3,]  3  6

Addition/subtraction can be performed using standard functions

y=c(1,1,1)
x
   [,1] [,2] [,3]
x1    1    2    3
x2    4    5    6
x-y
   [,1] [,2] [,3]
x1    0    1    2
x2    3    4    5

Multiplication can be performed using

%*%
x
   [,1] [,2] [,3]
x1    1    2    3
x2    4    5    6
y
[1] 1 1 1
#NOTE: c() specifies as a column vector, so y is 3 x 1

x%*%y
   [,1]
x1    6
x2   15
#Verifying results were correct
1*1+1*2+1*3
[1] 6
1*4+1*5+1*6
[1] 15

and the inverse can be taken as solve()

solve(rbind(c(1,2,3),
            c(1,4,9),
            c(1,8,27)))
           [,1] [,2]       [,3]
[1,]  3.0000000 -2.5  0.5000000
[2,] -1.5000000  2.0 -0.5000000
[3,]  0.3333333 -0.5  0.1666667

Determinant can be identified using det()

det(rbind(c(1,2,3),
          c(1,4,9),
          c(1,8,27)))
[1] 12

Real Data

The dataset that will be the primary example through this program is from a randomized trial of a gratitude based intervention. Research has demonstrated a strong association between reported feelings of gratitude and other measures of psychological and physiological well-being. But correlation is not necessarily causation, so we were curious whether or not intentionally practicing gratitude can improve measures of mental health and reduce stress responsiveness. We had a protocol where we subjected participants to the Trier Stress Test, which includes five stages: baseline, preparing a speech, performing a speech in front of the researchers, doing arithmetic in front of the researchers, and recovery. During each stage of this protocol, we recorded the participant’s heart rate to track in real time how they physiologically responded to stress. We also asked them to fill out some questionnaires pre and post stress task, and took measures of salivary cortisol, a stress hormone, before and after the stress protocol.

This provided a snapshot of how participants experienced stress at one point in time, however we were curious to see how intentionally practicing gratitude impacted this! To understand the impact of gratitude, we asked participants to go through this protocol twice! We asked everybody to do the stress task when they first enrolled in the study. Then, we randomly assigned participants to experimental and control conditions. The experimental group was asked to practice gratitude by writing down three things they were thankful for every day for two weeks. The control group was asked to journal about three life events every day for two weeks. At the end, participants were asked to come back and do the stress task again! Because gratitude and control groups were randomized, we did not anticipate meaningful differences between groups when they first started the protocol at baseline. However, after the two week period, we thought participants who practiced gratitude would demonstrate higher levels of subjective well-being, less salivary cortisol, and lower heart rate during the stress task protocol. This allowed us to test this empirically, and aspects of this will be examined throughout this program!

I have found it is simplest to read data into R in the form of a text file. If you copy and paste data from Excel into a text file, there’s little room for processing problems! This code will read in the data for the file location on my machine, but you’ll need to update the location and name on your machine.

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

To just look at the first few rows, you can use head(). I won’t run that here for privacy reasons, but it’s an easy check that the data successfully imported!

head(data)

You can also pull up the whole table using View().

View(data)

Basic statistics

We can calculate the average with mean()

#Baseline heart rate at the first iteration of the stress protocol
mean(data$HRBASE1)
[1] 75.3119
#Baseline heart rate at the second iteraation of the stress protocol
mean(data$HRBASE2)
[1] 75.5631

We can subset by the two conditions to simplify working with raw data

(NOTE: For analysis, better to keep data together, this is just for making charts and exploratory work!)

#The CONDITION variable indicates which group they were randomized to:
#1 if gratitude, 2 if control
grat=subset(data,data$CONDITION==1)
ctrl=subset(data,data$CONDITION==2)

#There should be 21 participants per group for a total of 42
nrow(data)
[1] 42
nrow(grat)
[1] 21
nrow(ctrl)
[1] 21

This was randomized, so we don’t think there should be a difference in average heart rate at the first baseline prior to randomization, but it’s good to confirm that in the data!

#Heart rate at the recovery stage of the protocol during the first iteration of the protocol
mean(grat$HRRECOV1)
[1] 72.90476
mean(ctrl$HRRECOV1)
[1] 71.1
mean(grat$HRRECOV1)-mean(ctrl$HRRECOV1)
[1] 1.804762

So there’s a slight difference, but a couple beats per minute isn’t huge! Let’s check now if there’s something more going on after they completed the intervention! Again, because it was randomized, we are hypothesizing gratitude is lower and the cause was the intervention!

#Heart rate at the recovery stage of the protocol during the second iteration of the protocol
mean(grat$HRRECOV2)
[1] 73.71429
mean(ctrl$HRRECOV2)
[1] 74
mean(grat$HRRECOV2)-mean(ctrl$HRRECOV2)
[1] -0.2857143

That is a bit surprising, the difference now is only about a third of a beat per minute! May be worth looking into this more, and charts might provide clearer insights than itemized statistics!

Making charts

Histograms

The histogram is arguably the most important chart in statistics! The X axis represents the values of a variable, and the Y axis represents the frequency. If you’ve ever heard about the “bell curve”, that is in reference to a histogram. In essence, for many numeric measures, most of the values will be close to the average in the middle, with some above and below the average. The resulting histogram has many frequencies toward the center values with relatively few on the left or right, like a bell shape! We’ll talk more about this in the topic 3, but that’s why histograms are so important, they give us a snapshot of a single measure, where the values tended to be!

Here is a histogram for heart rate during recovery at the second iteration of the protocol. We hypothesize that gratitude will tend toward lower values. We’ll split by gratitude and control groups, so we can make that comparison visually!

hist(grat$HRRECOV2,
     main="Histogram of Recovery Heart Rate at First Trial",
     xlab="Recovery Heart Rate at First Trial, Gratitude Group")

hist(ctrl$HRRECOV2,
     main="Histogram of Recovery Heart Rate at First Trial",
     xlab="Recovery Heart Rate at First Trial, Control Group")

It looks like there might be more variation in heart rates for the control group, since the scaling goes a bit lower and higher for that group. While the histogram gives a lot of detail on the individual measure, multiple measures can be more easily compared with other charts by plotting the averages.

Bar Charts

A bar chart represents numeric information on the Y axis and groups on the X axis. You can plot anything you like, oftentimes a bar chart might be used to plot the averages on the Y axis for meaningful separate groups on the X axis.

We’ll plot the average of the mean heart rate at each stage of the protocol between the two groups, to see if there obvious differences in changes over time

means_grat=c(colMeans(grat[,6:15]))
means_ctrl=c(colMeans(ctrl[,6:15]))

#Long names wouldn't fit on the plot,
#so shortening to five stages of a protocol on two occasions
names(means_grat)=c("1.1","1.2","1.3","1.4","1.5",
                    "2.1","2.2","2.3","2.4","2.5")
names(means_ctrl)=c("1.1","1.2","1.3","1.4","1.5",
                    "2.1","2.2","2.3","2.4","2.5")

Making the charts

barplot(means_grat,
        main="Heart Rates for Gratitude Group",
        xlab="Measurement")

barplot(means_ctrl,
        main="Heart Rates for Control Group",
        xlab="Measurement")

Visually, I’m not sure yet that I can discern large differences between the two groups, so we’ll need to keep thinking it through!

Line Charts

Line charts are conceptually the same as bar charts, the difference is you connect each value with lines rather than making them discrete bars! I find this especially valuable when examining changes over time. Examining the bar charts and histograms, it was difficult to compare between groups visually. But with a line chart, we can make two lines and directly evaluate the extent to which they overlap!

This time, let’s plot the averages for each stage of the protocol at the first and second iterations of the protocol to see how they directly compared. We can scale time from 1-5 because there are five stages. Additionally, if we use the lines() statement, it will add a line to a chart that is already created! The legend() statement will create a legend, and you can specify its location using X and Y coordinates or simply a verbal phrase of general location! The names and colors are specified in the legend and col inputs, lty specifies if you want solid lines or dashed (1 for solid, higher numbers for different dash types).

x=c(1:5)
plot(x=x,y=means_ctrl[1:5],type="l",ylim=c(70,90),
     main="Heart Rates by Experimental Condition, Pre",
     xlab="Stage of Protocol",
     ylab="Mean Heart Rate")
lines(x=x,y=means_grat[1:5],col="red")
legend("topleft",
       legend=c("Control","Gratitude"),
       col=c("black","red"),
       lty=c(1,1))

plot(x=x,y=means_ctrl[6:10],type="l",ylim=c(70,90),
     main="Heart Rates by Experimental Condition, Post",
     xlab="Stage of Protocol",
     ylab="Mean Heart Rate")
lines(x=x,y=means_grat[6:10],col="red")
legend("topleft",
       legend=c("Control","Gratitude"),
       col=c("black","red"),
       lty=c(1,1))

Visually, it seems like the gratitude group showed slightly higher heart rates across the entire first iteration of the protocol, which is concerning since they were randomized and had not completed the gratitude intervention yet. At post, the gratitude group started out higher again on average, but at the end of the stress protocol, they seem to have gotten close to the heart rates of the control group or even decreased slightly! This might be relevant in thinking through how we approach analysis!

Box Plot

Box plots represent the distribution of numeric data, like if you looked at the histogram from above. The edges of the box represent the middle 50% of the data, with a line for where the median is (the 50th percential, the number in the very middle of the data). The whiskers are scaled out based on the variation in the data to represent most of the data. Extreme values are represented with points above or below the whiskers. This helps to give some visual sense of what values were most common, and where there were any surprising observations.

First we should creating some labels to keep organized!

data$group=ifelse(data$CONDITION==1,"Gratitude","Control")
#Factors are categorical data, can be plotted as boxplots easily!
data$group=as.factor(data$group)

What the plots so far have told us is it that it seems like the gratitude group had higher averages at the first stage of the protocol by chance. To address this, it might be worth doing a difference statistic, comparing the CHANGE in heart rate from the first iteration of the protocol to the second iteration of the protocol. Then, aware that by chance the gratitude group had some people with high heart rates, we will at least be able to account for that in our comparison after the intervention is complete!

#Focusing on recovery heart rate, defining this has change in heart rate
#from the first iteration of the protocol
data$Delta_HR=data$HRRECOV2-data$HRRECOV1

plot(data$Delta_HR~data$group,
        main="Change in Revovery Heart Rate Pre to Post Intervention by Group",
        xlab="Intervention Group",
        ylab="Change in Recovery Heart Rate")

Visually, this gives some hope for the gratitude trial! Most participants showed increases in heart rate, but the gratitude group showed less variation with a few people who showed distinct decreases in heart rate! Throughout this program, we’ll consider ways to investigate comparisons like this in more detail, but this has provided some early starting places for how to explore data and use R!

Key Takeaways

  • R is capable of all kinds of tasks
  • This has reviewed some basic calculator functions and plots
  • Because R is crowdsourced, there’s a lot more you can do than this has covered
  • Most notably, this did not cover ggplot, one of the most popular (but more complex) graphing tools in R
  • Check online, the R community is very active, and responsive to individual questions and comments on forums!

Topic 2: Research Design Basics

Learning Goals

There’s common research designs that provide a practical language for discussing and describing your choices, however at the end of the day all that matters is connecting theory to hypothesis. What question are you asking, what information will help you answer it, and what concerns or limitations remain? This will provide an example of posing and investigating a couple research questions, one experimental (i.e., manipulation by the researcher), the other observational (i.e., no manipulation). Importantly, higher powered analytics will follow, but this will provide an overview of conceptual starting places.

Packages used:

  • psych
library(psych)

Experimental Approach

Comparing randomized conditions in gratitude trial

  • Theory: Gratitude changes the way a person perceives events, which will mean reduced stress response when posed with a challenge and greater subsequent happiness because of it
  • Hypothesis: Participants practicing gratitude will have lower levels of cortisol after the two week experimental period relative to control
  • Threat to validity: Not everybody will follow through on the assigned experimental condition
  • Threat to validity: By random chance, participants will not be directly comparable

First we need to get the data in:

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

To address the threats to validity, we should check to make sure there weren’t problems with participants actually following through on their assigned condition or with comparability of the randomized groups.

The describe() function in the psych package provides a quick overview of descriptive statistic, and table() presents frequencies.

describe(data$DAYSOFUSINGAPP)
   vars  n  mean   sd median trimmed mad min max range  skew kurtosis   se
X1    1 42 13.19 1.44     14   13.53   0   8  14     6 -2.02     3.63 0.22
#Extract frequencies
table(data$DAYSOFUSINGAPP)

 8  9 10 11 12 13 14 
 1  1  1  1  5  6 27 
barplot(table(data$DAYSOFUSINGAPP),
        main="App Usage",
        xlab="Days Using App (14 Max)",
        ylab="Frequency")

Most people seem to have done their experimental condition properly, but let’s compare between conditions

data$group=ifelse(data$CONDITION==1,"Gratitude","Control")

data$group=as.factor(data$group)

plot(data$DAYSOFUSINGAPP~data$group,
        main="App Usage By Group",
        xlab="Experimental Group",
        ylab="Days Using App")

Seems like compliance wasn’t an issue! Another possible issue: what if by chance randomized groups aren’t similar? Let’s start with age. The describeBy() function also in the psych package performs the same process as the describe() function, but disaggregating by a given group, in this case the experimental and control conditions!

describeBy(data$AGE,data$group)

 Descriptive statistics by group 
group: Control
   vars  n  mean   sd median trimmed  mad min max range skew kurtosis   se
X1    1 21 20.33 1.77     20   20.29 1.48  18  23     5 0.19    -1.57 0.39
------------------------------------------------------------ 
group: Gratitude
   vars  n  mean   sd median trimmed  mad min max range skew kurtosis   se
X1    1 21 20.57 3.45     20   19.88 1.48  18  34    16 2.76     8.02 0.75

We can also use histograms as a guide! Adding “add=T” to the hist() code tells it to overlay the two histograms.

hist(subset(data,data$CONDITION==1)$AGE,
     main="Histogram of Ages By Group",
     xlab="Age",breaks=15,
     ylim=c(0,11))
hist(subset(data,data$CONDITION==2)$AGE,
     add=T,col="red",breaks=5)

Ages seem to be comparable outside of the one person who was distinctly older. Let’s get a sense of what cortisol was like as a distribution.

describe(cbind(data$CortBase1,data$CortStress1,
               data$CortBase2,data$CortStress2))
   vars  n mean   sd median trimmed  mad  min  max range skew kurtosis   se
X1    1 42 0.21 0.15   0.18    0.19 0.10 0.01 0.87  0.86 2.29     8.03 0.02
X2    2 42 0.24 0.29   0.19    0.20 0.15 0.02 1.93  1.91 4.45    22.70 0.05
X3    3 42 0.24 0.25   0.18    0.19 0.12 0.03 1.54  1.52 3.56    15.29 0.04
X4    4 42 0.22 0.17   0.18    0.19 0.11 0.04 0.78  0.74 1.74     2.51 0.03

Let’s take a closer look visually. Before we used the hist() function, but that may be too blocky for all the charts we want to overlay! We can make a line chart of the implied histogram using the plot() function like before, but make the plot of the density of each variable, using the density() function. This is analogous to tracing the outline of the histogram. We can also change the lty input to change between solid and dashed lines!

plot(density(data$CortBase1),
     main="Histogram of Cortisol",
     xlab="Cortisol",
     xlim=c(0,2),
     col="black",
     lty=1)
lines(density(data$CortStress1),
     col="red",lty=1)
lines(density(data$CortBase2),
      col="black",lty=2)
lines(density(data$CortStress2),
      col="red",lty=2)
legend("topright",
       legend=c("Baseline 1",
                "Stress 1",
                "Baseline 2",
                "Stress 2"),
       col=c("black","red","black","red"),
       lty=c(1,1,2,2))

This gives us a sense of what cortisol levels were common, but that’s also a bit general. Going back to that second threat to validity, it might be worth specifically comparing cortisol levels at baseline by experimental condition. Because if randomization was successful, these groups should be similar! Otherwise, sampling chance may have gotten the best of us!

Note that log=“y” requests that the Y axis be on a log scale. You can specify the X axis to be on a log scale using log=“x”, or both axes using log=“xy”. Since the X axis is a group, we’ll just log scale the Y axis for now!

plot(data$CortBase1~data$group,
     log="y",
     main="Baseline Cortisol by Group",
     xlab="Experimental Group",
     ylab="Baseline Cortisol, First Protocol")

plot(data$CortStress1~data$group,
     log="y",
     main="Stress Cortisol by Group",
     xlab="Experimental Group",
     ylab="Stress Cortisol, First Protocol")

I’m not seeing vast differences in averages, but they do seem to have some differences in variation! Having some sense of the context, we can think about our hypothesis some more! Let’s start with a plot! If the gratitude group is less stressed, then at this second iteration of the protocol, cortisol should be lower on average. Let’s see if it played out like that!

plot(data$CortBase2~data$group,
     log="y",
     main="Baseline Cortisol by Group",
     xlab="Experimental Group",
     ylab="Baseline Cortisol, Second Protocol")

plot(data$CortStress2~data$group,
     log="y",
     main="Stress Cortisol by Group",
     xlab="Experimental Group",
     ylab="Stress Cortisol, Second Protocol")

Looks like there might be some differences in averages, but the variation around the averages is quite different for the groups, so it’s hard to draw a clear conclusion! Let’s consider a data transformation to try to understand this better! I’m going to do a ratio that can be interpreted as how much more cortisol participants had excreted as a multiple of individual baseline levels!

data$Cort_Delt2=data$CortStress2/data$CortBase2

And let’s make a chart

plot(data$Cort_Delt2~data$group,
     log="y",
     main="Change in Cortisol by Group",
     xlab="Experimental Group",
     ylab="Change in Cortisol from Second Baseline")

and for a more precise statistic, we can use the describeBy() function

describeBy(data$Cort_Delt2,group=data$group)

 Descriptive statistics by group 
group: Control
   vars  n mean   sd median trimmed  mad min  max range skew kurtosis   se
X1    1 21 1.23 0.56   1.08     1.2 0.63 0.5 2.25  1.75 0.41     -1.2 0.12
------------------------------------------------------------ 
group: Gratitude
   vars  n mean   sd median trimmed  mad  min  max range skew kurtosis   se
X1    1 21 1.08 0.67   0.87    0.94 0.34 0.43 3.14  2.72 1.74     2.37 0.15

Together this provides some broad support for the gratitude intervention! For both groups, some people increased cortisol while others decreased. However, on average the gratitude group increased by 8%, while the control group increased by 23%, which is what we would see if the gratitude condition is helping people manage stress! In the next topics, we’ll identify ways to make more precise comparisons of these changes, but this is a good start!

Observational Approach

Comparing groups based on language barriers

  • Theory: Language barriers could prohibit some students from effective learning, adding to the challenges of being a student in another country
  • Hypothesis: Participants from countries where the primary languages spoken do not include English will have higher cortisol levels while giving a speech to the researchers in English
  • Threat to validity: To compare international students to domestic students, differences could be attributable to cultural differences rather than language in specific
  • Threat to validity: Students with the means to travel to another country for education may not generalize well to all students with a language barrier

First let’s process the data a bit to distinguish these groups

data$Language=ifelse(data$Nationality_Language=="International_Non_Eng","Barrier","No Barrier")

That first threat to validity may be beyond empirical investigation with these data, but we can address the second threat to validity! Let’s start with ages again!

describeBy(data$AGE,group=data$Language)

 Descriptive statistics by group 
group: Barrier
   vars  n  mean   sd median trimmed  mad min max range skew kurtosis   se
X1    1 20 20.27 1.58     20   20.15 1.48  18  23     5 0.55    -1.16 0.35
------------------------------------------------------------ 
group: No Barrier
   vars  n  mean   sd median trimmed  mad min max range skew kurtosis   se
X1    1 22 20.61 3.47     20   19.97 2.22  18  34    16 2.54     7.21 0.74
plot(density(subset(data,data$Language=="Barrier")$AGE),
     xlim=c(17,35),
     main="Ages by Language Barrier",
     xlab="Age",
     col="red")
lines(density(subset(data,data$Language=="No Barrier")$AGE),
     col="black")
legend("topright",
       legend=c("Barrier","No Barrier"),
       col=c("red","black"),
       lty=c(1,1,1))

Looks like ages are pretty similar between both groups, but the students without a language barrier include that one person who is much older than expected! Let’s take a look at gender

data$Gender_Label=ifelse(data$GENDER==1,"Male","Female")
table(data$Language,data$Gender_Label)
            
             Female Male
  Barrier        16    4
  No Barrier     16    6

That’s good that there’s parity by gender between groups, though we are seeing a lot more women than men. This is very common for psychology students, so we’ll need to keep that in mind.

Let’s take out that much older person before looking at cortisol, in case it messes things up! (NOTE: Be careful in tossing people out of an analysis, every choice you make needs to be justified!)

data2=subset(data,data$AGE<26)
describe(cbind(data2$CortBase1,data2$CortStress1))
   vars  n mean   sd median trimmed  mad  min  max range skew kurtosis   se
X1    1 41 0.21 0.15   0.19    0.19 0.10 0.01 0.87  0.86 2.26     7.87 0.02
X2    2 41 0.25 0.30   0.19    0.20 0.15 0.02 1.93  1.91 4.43    22.33 0.05
hist(data2$CortStress1,
     main="Histogram of Cortisol",
     xlab="Cortisol",
     xlim=c(0,2),
     breaks=15,col="red")
hist(data2$CortBase1,
     breaks=15,add=T)

Doing a direct comparison, groups should not be different at baseline!

data2$Language=as.factor(data2$Language)

plot(data2$CortBase1~data2$Language,
     log="y",
     main="Baseline Cortisol by Language Barrier",
     xlab="Language Barrier",
     ylab="Baseline Cortisol")

But we do expect a difference after the stress task!

plot(data2$CortStress1~data2$Language,
     log="y",
     main="Stress Cortisol by Language Barrier",
     xlab="Language Barrier",
     ylab="Stress Cortisol")

and like before, we might want to look at this in terms of change in cortisol, as a percentage!

data2$Cort_Delt=data2$CortStress1/data2$CortBase1

plot(data2$Cort_Delt~data2$Language,
     log="y",
     main="Change in Cortisol by Language Barrier",
     xlab="Language Barrier",
     ylab="Change in Cortisol")

describeBy(data2$Cort_Delt,group=data2$Language)

 Descriptive statistics by group 
group: Barrier
   vars  n mean  sd median trimmed  mad  min   max range skew kurtosis   se
X1    1 20 1.88 2.9   1.05    1.24 0.61 0.45 13.88 13.43 3.52    11.71 0.65
------------------------------------------------------------ 
group: No Barrier
   vars  n mean  sd median trimmed  mad  min  max range skew kurtosis   se
X1    1 21 1.05 0.6   0.88    0.97 0.28 0.36 2.34  1.98 1.16    -0.13 0.13

Putting it all together, it visually does appear to be some support for the hypothesis about a language barrier may exacerbate stress during a speech task! On average, participants without a known language barrier increased in cortisol by 5%, compared to the 88% increase among participants who might have a language barrier! As mentioned before, this could be more representative of cultural differences rather than a language barrier in specific, so we need to be careful. But it is consistent with the hypothesis!

Key Takeaways

  • There’s a common language for research design that can help to describe your thinking
  • But at the end of the day, you need to explain the reasons pieces of information will help answer your question…
  • …and the limitations that your analysis cannot address!
  • Successful use of statistics in science is aligning data you can collect with a question you can answer, and one size does not fit all!

Topic 3: Introduction to Probability Theory

Learning Goals

The focus of today will be probability theory and properties of random variables. Most basic probability functions can largely be accomplished using base R functions. Specifically, there are four function prefixes:

  • d: calculate a probability for given x (i.e., p(X=x), x probability input as x)
  • p: calculate a probability x greater than or equal to (i.e., p(X<=x), cumulative probability input as q)
  • q: calculate implied value of x for qiven quantile (quantile input as p)
  • r: simulate random variables from distribution (number of random variables input as n)

Each of these can be used with distribution suffix to perform the same procedures. In this section, we will focus on the density function (d prefix) rather than the cumulative density function (p prefix), because this is analogous to the histogram you could obtain by sampling from that probability distribution. The cumulative density function is very important for hypothesis testing, the next topic, but has less intuitive relevance.

Packages used:

  • psych
  • MASS
  • Ray’s functions
library(MASS)
source("https://raw.githubusercontent.com/JoshuaRayTanzer/Functions/main/Functions.R")

Binomial distribution

A binomial distribution represents a discrete event, something that either does not happen (denoted 0) or does happen (denoted 1), and the probability of the event happening is denoted \(\pi\). The \(\pi\) parameter is provided in the prob input. Additionally, you can consider the scenario of multiple binomial events occuring, provided in the size input. The suffix for the binomial distribution in R is binom.

Let’s use the classic example of flipping a coin that turns up heads!

#probability of heads
dbinom(x=0,size=1,prob=0.5)
[1] 0.5
#probability of tails
dbinom(x=1,size=1,prob=0.5)
[1] 0.5
#simulation flipping a coin ten times
rbinom(n=10,size=1,prob=0.5)
 [1] 1 0 0 0 1 0 1 0 0 0

Can be extrapolated to many flips

#probability of exactly three heads out of ten flips
dbinom(x=3,size=10,prob=0.5)
[1] 0.1171875
#how many heads would represent the 30th percentile
qbinom(p=0.3,size=10,prob=0.5)
[1] 4
#flip ten coins and count the heads
rbinom(n=1,size=10,prob=0.5)
[1] 5
#flip ten coins and count the heads ten times
rbinom(n=10,size=10,prob=0.5)
 [1] 7 3 5 5 4 3 6 5 3 6
#I know that's silly business, but worth keeping straight
#the difference between n (number of iterations)
#and size (number of flips per iteration)

We can also plot the distribution!

Start by giving a range of values to plot

x=seq(0,1,length=100)
x
  [1] 0.00000000 0.01010101 0.02020202 0.03030303 0.04040404 0.05050505
  [7] 0.06060606 0.07070707 0.08080808 0.09090909 0.10101010 0.11111111
 [13] 0.12121212 0.13131313 0.14141414 0.15151515 0.16161616 0.17171717
 [19] 0.18181818 0.19191919 0.20202020 0.21212121 0.22222222 0.23232323
 [25] 0.24242424 0.25252525 0.26262626 0.27272727 0.28282828 0.29292929
 [31] 0.30303030 0.31313131 0.32323232 0.33333333 0.34343434 0.35353535
 [37] 0.36363636 0.37373737 0.38383838 0.39393939 0.40404040 0.41414141
 [43] 0.42424242 0.43434343 0.44444444 0.45454545 0.46464646 0.47474747
 [49] 0.48484848 0.49494949 0.50505051 0.51515152 0.52525253 0.53535354
 [55] 0.54545455 0.55555556 0.56565657 0.57575758 0.58585859 0.59595960
 [61] 0.60606061 0.61616162 0.62626263 0.63636364 0.64646465 0.65656566
 [67] 0.66666667 0.67676768 0.68686869 0.69696970 0.70707071 0.71717172
 [73] 0.72727273 0.73737374 0.74747475 0.75757576 0.76767677 0.77777778
 [79] 0.78787879 0.79797980 0.80808081 0.81818182 0.82828283 0.83838384
 [85] 0.84848485 0.85858586 0.86868687 0.87878788 0.88888889 0.89898990
 [91] 0.90909091 0.91919192 0.92929293 0.93939394 0.94949495 0.95959596
 [97] 0.96969697 0.97979798 0.98989899 1.00000000

and making the chart based on the density of each value of X chosen

plot(x=x,y=dbinom(x,size=1,prob=0.5),type="l",
     main="Any Binomial Probability",
     xlab="Value of X",
     ylab="Probability")

A coin flip with 50% probability is a bit obvious, but you could find more interesting results with other probabilities!

prob=0.25

plot(x=x,y=dbinom(x,size=1,prob=prob),type="l",
     main="Any Binomial Probability",
     xlab="Value of X",
     ylab="Probability")

Poisson distribution

The poisson distribution is often used for count data. Technically, it represents how many binomial events will occur in a specified period of time for a given rate, \(\lambda\). The \(\lambda\) parameter is equal to the mean, so \(\lambda\) = 2 implies the average will be 2. The suffix for a Poisson distribution in R is pois

dpois(x=3,lambda=2) #probability of exactly three events occurring in the period of time
[1] 0.180447
qpois(p=0.95,lambda=2) #how many events would represent the 95th percentile in the period of time
[1] 5
rpois(n=10,lambda=2) #Observe 10 Poisson counts
 [1] 4 3 1 3 2 5 2 0 1 2
#to fact check that lambda equal to the mean statement, we can verify this!
mean(rpois(n=40,lambda=2))
[1] 2.15

Like before we can plot the Poisson probability density, which just represents the histogram we’d expect to see if we collected poisson data

rate=3
#inferring how far out to go based on a chart to represent 99% of the distribution
upper_limit=qpois(0.99,rate)

x=0:upper_limit
plot(x=x,y=dpois(x,lambda=rate),type="l",
     main="Any Poisson Probability",
     xlab="Value of X",
     ylab="Probability")

Negative binomial distribution

The details on negative binomial are beyond this program, but it is worth some broad familiarity! The negative binomial distribution is characterized by a heavy right tail and lots of values close to zero but that cannot go BELOW zero! Some count data aren’t well represented by a Poisson distribution, especially if there are extreme high values. Negative binomial distributions are more flexible to represent the data if there is a real possibility of extreme numbers much larger than where the majority of the counts are! The suffix for negative binomial distributions in R is nbinom.

upper_limit=qnbinom(0.99,size=3,prob=0.5)

x=0:upper_limit
plot(x=x,y=dnbinom(x,size=3,prob=0.5),type="l",
     main="Negative Binomial Probability",
     xlab="Value of X",
     ylab="Probability")

Exponential distribution

Exponential data represent a rate variable that can assume any value, not just whole numbers but decimals as well. Additionally, exponential data always have a sloping probability distribution that historically has been interpreted in terms of the amount of time between events and in natural science rate of decay and excretion. Values have to be greater than zero, but the probability of larger values consistently decreases at a consistent rate given by a rate parameter \(\lambda\). The average is equal to \(1/\lambda\) (as well as more detailed interpretation for halflives and time to event, but that’s a different course!). The suffix for exponential distributions in R is exp.

It is also worth noting that for continuous distributions (like exponential, because values could be any number even decimals) the probability density function (d prefix, dexp for exponential) return values that cannot be interpreted as a raw probability. For counts, each density represents the probability of that individual count being observed, but for continuous values there’d be too many probabilities! Instead, the probability density function for continuous data needs to be interpreted as representing a value scaling the probability of that value to all other possible numeric values. Because of this, there may be values that do not make interpretable sense as probabilities, such as values greater than 1 (nothing can be more probable than 100%). This is because density is scaled to probability, but does not necessarily directly represent probability.

dexp(x=0.3,rate=1/2) #density of an exact score of 0.3
[1] 0.430354
qexp(p=0.667,rate=1/2) #what level would represent the two thirds percentile
[1] 2.199226
rexp(n=10,rate=1/2) #Observe 10 exponential events
 [1] 2.92439516 1.45697602 1.49356133 0.29876995 0.02107674 0.25287951
 [7] 2.06757194 3.26717234 4.35440591 2.79177705
#again to fact check the relationship between rate and average, should be 2
mean(rexp(n=40,rate=1/2))
[1] 1.761032

Plotting any exponential probability density

rate=1/2
upper_limit=qexp(0.99,rate)

x=seq(0,upper_limit,length=100)
plot(x=x,y=dexp(x,rate=rate),type="l",
     main="Any Exponential Probability",
     xlab="Value of X",
     ylab="Density")

And note that if we increase the rate parameter to be much larger, implying an average of 100, the shape of the probabilities over the range of values is equivalent even though the actual numbers are quite different! This is one of the hallmark traits of the exponential distribution!

rate=1/100
upper_limit=qexp(0.99,rate)

x=seq(0,upper_limit,length=100)
plot(x=x,y=dexp(x,rate=rate),type="l",
     main="Any Exponential Probability",
     xlab="Value of X",
     ylab="Density")

The gamma distribution is a generalization of the exponential distribution. This program won’t cover it in detail, but the codes are dgamma, pgamma, qgamma, and rgamma. It is worth being familiar with the name because some codes we’ll be using in later topics only work with the name “gamma” rather than exponential!

Beta distribution

A beta distribution is often used for data that are percentages. The values of a beta distribution are always between 0 and 1, however different than a binomial distribution they can be decimals. For example, scores on a school test might be characterized as beta distributed because you could earn 80% or 90%–as high as 100% or as low as 0%! The practical value of using the beta distribution is that it represents the “ceiling” and “floor” effects at 0 and 1. If everybody in class does pretty well on the test, most people will be bunched up in the 90s, but a few people will have lower scores. A beta distribution represents this well! It has \(\alpha\) and \(\beta\) shape and scale parameters, which may or may not have a practical interpretation. More importantly is being aware of this distribution so that you can account for it in how you understand data you collect! The suffix for beta distributions in R is beta.

As mentioned before, for continuous distributions, the density function (d prefix, dbeta for a beta distribution) provides values representing densities scaled proportionally to probability rather than raw probabilities as were provided by count distributions! In the case of a beta distribution, in many cases the density values will be above one! While density cannot be negative, it can be any positive number so long as it proportionally represents probability in relation to all other density values! Oftentimes the beta distribution has asymptotes at 0 and 1, meaning that the density gets infinitely large as you get closer to the scaling limits.

dbeta(x=0.3,shape1=3,shape2=5) #density of an exact score of 0.3
[1] 2.268945
#note how densities can be greater than 1, and beta goes to infinity near 0 and 1!
qbeta(p=0.5,shape1=3,shape2=5) #what level would represent the median
[1] 0.3641161
rbeta(n=10,shape1=3,shape2=5) #Observe 10 beta percentages
 [1] 0.6693841 0.3968531 0.2132502 0.1242600 0.4125875 0.3246785 0.2851767
 [8] 0.3286559 0.3895742 0.6842871

Plotting any beta probability density

shape1=2
shape2=4

x=seq(0.005,0.995,length=100)
#As hinted at before, 0 and 1 are asymptotes, so need to restrict our range a bit!

plot(x=x,y=dbeta(x,shape1=shape1,shape2=shape2),type="l",
     main="Any Beta Probability",
     xlab="Value of X",
     ylab="Density")

Normal distribution

The normal distribution is the bell curve with center parameter \(\mu\) and spread parameter \(\sigma^2\). In R, the input center parameter mean represents the mean and the input spread parameter specifically represents the standard deviation. The suffix for the normal distribution in R is norm.

dnorm(x=-1,mean=0,sd=1) #density of an exact score of -1
[1] 0.2419707
qnorm(p=0.25,mean=0,sd=1) #what score would represent the 25th percentile
[1] -0.6744898
rnorm(n=10,mean=0,sd=1) #Observe 10 standard normals
 [1]  0.6940337  1.3875363  0.2091062 -0.3365166 -1.2333565  0.4218885
 [7]  0.1367736  1.1993656  1.8703153 -1.0055879

Plotting any normal probability density

mean=100
sd=15

x=seq(mean-3*sd,mean+3*sd,length=100)

plot(x=x,y=dnorm(x,mean=mean,sd=sd),type="l",
     main="Any Normal Probability",
     xlab="Value of X",
     ylab="Density")

The t distribution is a specific case of the normal distribution for when the true standard deviation/variance is unknown and needs to be estimated from a sample of data. Most relevantly, in most scientific applications, you are using the sample to estimate the mean and variance, so we need to be cautious with our probabilities to avoid thinking our estimates are more precise than they should be! To address this, the tails are heavier for a t distribution, but there is an extra parameter denoted \(\nu\) called degrees of freedom that scales the weight in the tails to the sample size. If the sample is small, it assumes there is a greater probability of high values or low values. If the sample is large, the distribution converges to a standard normal distribution. The codes for the t distribution are dt, pt, qt, and rt.

Expectations and Variances

A key goal of probability theory is knowing what to expect when you do math on the data. Because randomness will always result in some surprises, we need to make sure the steps we take in processing data is actually helping us understand the data, rather than just adding more variability to something that’s already random! The expectation (E(X)) represents the average value you anticipate, and the variance (V(X)) represents the variation across the range of values the variable can take. We often estimate these in data by the mean and standard deviation (which is the square root of variance). If you add, subtract, multiply, and divide variables by other numbers, this will have different implications for the average and variation. This will provide some demonstration and overview of how different mathematical operations will change what we find in random variables!

Let’s start by generating 5000 standard normal observations

x=rnorm(5000,mean=0,sd=1)

We know from the normal distribution, the expectation is the mean parameter (0 in this case), and the variance is the variance parameter (1 in this case). In statistics notation, E(X) = 0, and V(X) = 12 = 1. Let’s confirm!

mean(x)
[1] -0.01100045
var(x)
[1] 0.9937798

Technically, these are slightly different from the known expected value and variance, but that always happens with observed data, it wouldn’t be random if we got the exact expected value and variance every time! What’s important is that it’s close, and as we collect larger samples, we’ll get even closer!

But that was a kind of boring example, let’s do another, this time with more interesting mean and variance parameters!

x=rnorm(5000,mean=10,sd=5)
#E(X) = 10
#V(X) = 5^2 = 25
mean(x)
[1] 10.04069
var(x)
[1] 25.79561

Now for some data transformations! Adding a constant does not change the variance but does increase the expected value by the value of the constant. Multiplying by a constant increases the expected value by the multiple of that constant, and increases the variance by a multiple of the value of that constant squared!

x=rnorm(5000,10,sqrt(9))

#E(aX+b) = a E(X) + b

#E(X+3) = E(X)+3 = 10+3 = 13
mean(x+3)
[1] 12.9723
#E(3X) = 3E(X) = 3*10 = 30
mean(3*x)
[1] 29.9169
#E(2X+5) = 2E(X)+5 = 2*10+5 = 25
mean(2*x+5)
[1] 24.9446
#V(aX+b) = a^2 V(X)

#V(X+3) = V(X) = 3^2 = 9
var(x+3)
[1] 9.187176
#V(3x) = 3^2*V(X) = 3^2 * 3^2 = 9*9 = 81
var(3*x)
[1] 82.68459
#V(2x+5) = 2^2*V(X) = 2^2 * 3^2 = 4*9 = 36
var(2*x+5)
[1] 36.7487

Adding random variables, the expectation of their sum is the sum of their expectations, even if they come from different probability densities. In this case, we’ll add a normal variable with mean parameter 30 and a Poisson variable with rate parameter 5 (implying mean 5), which should give us an average value for the mean at 35.

#E(X+Y) = E(X) + E(Y)
x=rnorm(5000,30,sqrt(5))
y=rpois(5000,lambda=5)

#E(X+Y) = E(X) + E(Y) = 30 + 5 = 35

mean(x+y)
[1] 35.04697

The variance is the sum of their variances plus twice their covariance (zero in this case).

#V(X+Y) = V(X) + V(Y) + 2*Cov(X,Y)

#V(X+Y) = V(X) + V(Y) + 2*Cov(X,Y) = 5 + 5 + 2*0 = 10
var(x+y)
[1] 10.42661

No covariance isn’t very interesting, let’s simulate correlated data! To do that, we need to specify a variance-covariance matrix! The variance-covariance matrix represents the variation within each variable and the covariation between to variables. On the diagonals are the variances for each variable, and the off diagonals has their covariance, which is defined as the correlation (which has a limited range from -1 to 1 where positive values mean when X happens, Y happens; negative values represent when X happens, Y does not happen) times the standard deviation of each variable (SD = sqrt(variance)). This results in a number representing common variation between the variables that is scaled to the variation within each variable.

v1=4
v2=9
rho=0.5

Sigma=matrix(nrow=2,ncol=2)
Sigma[1,1]=v1
Sigma[2,2]=v2
Sigma[1,2]=sqrt(v1)*sqrt(v2)*rho
Sigma[2,1]=sqrt(v1)*sqrt(v2)*rho
Sigma
     [,1] [,2]
[1,]    4    3
[2,]    3    9

We’ll also need to specify the averages of the two variables

mu=c(100,20)
mu
[1] 100  20

Now we can simulate data that are multivariate normal, meaning that they are two normal distributions that are correlated. This is accomplished using the mvrnorm() function in the MASS package

X=mvrnorm(5000,mu=mu,Sigma=Sigma)

To confirm the simulation worked properly!

colMeans(X)
[1] 99.99589 20.06341
var(X)
         [,1]     [,2]
[1,] 4.011461 2.992217
[2,] 2.992217 8.898349

And now to verify equivalence of the sums of dependent random variables

#V(X+Y) = V(X) + V(Y) +2*Cov(X,Y) = 4 + 9 + 2*3 = 19
Sigma[1,1]+Sigma[2,2]+2*Sigma[1,2]
[1] 19
#This is alternatively accomplished by just adding up
#all the values in the variance covariance matrix,
#because the diagonal is repeated twice!
sum(Sigma)
[1] 19
var(X[,1]+X[,2])
[1] 18.89424

And why not, let’s multiply by some constants to see what happens there as well!

a=3
b=4
c=19

#V(aX+bY+c) = a^2*X+b^2*X+2*a*b*Cov(X,Y) = 3^2*4+4^2*9+2*3*4*3
# = 9*4+16*9+24*3 = 36+144+72 = 252
a^2*Sigma[1,1]+b^2*Sigma[2,2]+2*a*b*Sigma[1,2]
[1] 252
var(a*X[,1]+b*X[,2]+c)
[1] 250.2899

Real Data

Basic descriptives easily done with psych package

library(psych)
data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

describe(data)
                      vars  n  mean    sd median trimmed   mad   min    max
CONDITION                1 42  1.50  0.51   1.50    1.50  0.74  1.00   2.00
RACE*                    2 42  8.98  5.29   6.00    8.91  4.45  1.00  18.00
NATIONALITY*             3 42 16.31  9.89  16.50   16.29 14.08  1.00  31.00
Nationality_Language*    4 42  2.12  0.92   2.00    2.15  1.48  1.00   3.00
RaceCategory             5 42  2.81  1.44   3.00    2.71  1.48  1.00   6.00
HRBASE1                  6 42 75.31 11.97  73.90   74.62 12.01 53.80 103.75
HRPREP1                  7 42 82.60 12.75  82.30   82.68 13.05 49.00 109.67
HRTALK1                  8 42 89.21 14.99  89.50   89.26 10.38 58.00 118.67
HRMATH1                  9 42 81.00 12.92  80.30   80.51 10.13 54.70 120.33
HRRECOV1                10 42 72.00 10.67  72.30   71.44 10.60 53.50  95.25
HRBASE2                 11 42 75.56 15.19  74.05   74.97 15.72 46.00 106.25
HRPREP2                 12 42 80.66 14.87  80.65   80.57 18.06 49.00 106.33
HRTALK2                 13 42 86.28 15.42  82.67   85.62 15.57 55.00 116.00
HRMATH2                 14 42 81.03 14.07  78.65   80.43 10.30 53.30 116.70
HRRECOV2                15 42 73.86 12.26  72.50   73.29 11.49 49.00 101.00
CortBase1               16 42  0.21  0.15   0.18    0.19  0.10  0.01   0.87
CortStress1             17 42  0.24  0.29   0.19    0.20  0.15  0.02   1.93
CortBase2               18 42  0.24  0.25   0.18    0.19  0.12  0.03   1.54
CortStress2             19 42  0.22  0.17   0.18    0.19  0.11  0.04   0.78
AGE                     20 42 20.45  2.71  20.00   20.09  1.48 18.00  34.00
GENDER                  21 42  1.76  0.43   2.00    1.82  0.00  1.00   2.00
DAYSOFUSINGAPP          22 42 13.19  1.44  14.00   13.53  0.00  8.00  14.00
PSS1                    23 42 40.05  5.95  39.00   39.74  4.45 29.00  55.00
PSS2                    24 42 39.83  7.29  39.00   39.35  7.41 27.00  56.00
PROMPT1                 25 42  1.48  0.51   1.00    1.47  0.00  1.00   2.00
PROMPT2                 26 42  1.52  0.51   2.00    1.53  0.00  1.00   2.00
                      range  skew kurtosis   se
CONDITION              1.00  0.00    -2.05 0.08
RACE*                 17.00  0.38    -1.21 0.82
NATIONALITY*          30.00 -0.03    -1.46 1.53
Nationality_Language*  2.00 -0.23    -1.80 0.14
RaceCategory           5.00  0.47    -0.55 0.22
HRBASE1               49.95  0.50    -0.42 1.85
HRPREP1               60.67 -0.18    -0.01 1.97
HRTALK1               60.67 -0.06    -0.46 2.31
HRMATH1               65.63  0.58     0.88 1.99
HRRECOV1              41.75  0.32    -0.58 1.65
HRBASE2               60.25  0.31    -0.77 2.34
HRPREP2               57.33  0.07    -1.01 2.30
HRTALK2               61.00  0.37    -0.75 2.38
HRMATH2               63.40  0.43    -0.09 2.17
HRRECOV2              52.00  0.41    -0.43 1.89
CortBase1              0.86  2.29     8.03 0.02
CortStress1            1.91  4.45    22.70 0.05
CortBase2              1.52  3.56    15.29 0.04
CortStress2            0.74  1.74     2.51 0.03
AGE                   16.00  2.95    12.09 0.42
GENDER                 1.00 -1.19    -0.61 0.07
DAYSOFUSINGAPP         6.00 -2.02     3.63 0.22
PSS1                  26.00  0.49    -0.20 0.92
PSS2                  29.00  0.52    -0.53 1.13
PROMPT1                1.00  0.09    -2.04 0.08
PROMPT2                1.00 -0.09    -2.04 0.08

That may be too much! We can also just focus on columns of interest! Columns 6 through 15 are the heart rate variables, let’s start there,

HR=data[,6:15]
describe(HR)
         vars  n  mean    sd median trimmed   mad  min    max range  skew
HRBASE1     1 42 75.31 11.97  73.90   74.62 12.01 53.8 103.75 49.95  0.50
HRPREP1     2 42 82.60 12.75  82.30   82.68 13.05 49.0 109.67 60.67 -0.18
HRTALK1     3 42 89.21 14.99  89.50   89.26 10.38 58.0 118.67 60.67 -0.06
HRMATH1     4 42 81.00 12.92  80.30   80.51 10.13 54.7 120.33 65.63  0.58
HRRECOV1    5 42 72.00 10.67  72.30   71.44 10.60 53.5  95.25 41.75  0.32
HRBASE2     6 42 75.56 15.19  74.05   74.97 15.72 46.0 106.25 60.25  0.31
HRPREP2     7 42 80.66 14.87  80.65   80.57 18.06 49.0 106.33 57.33  0.07
HRTALK2     8 42 86.28 15.42  82.67   85.62 15.57 55.0 116.00 61.00  0.37
HRMATH2     9 42 81.03 14.07  78.65   80.43 10.30 53.3 116.70 63.40  0.43
HRRECOV2   10 42 73.86 12.26  72.50   73.29 11.49 49.0 101.00 52.00  0.41
         kurtosis   se
HRBASE1     -0.42 1.85
HRPREP1     -0.01 1.97
HRTALK1     -0.46 2.31
HRMATH1      0.88 1.99
HRRECOV1    -0.58 1.65
HRBASE2     -0.77 2.34
HRPREP2     -1.01 2.30
HRTALK2     -0.75 2.38
HRMATH2     -0.09 2.17
HRRECOV2    -0.43 1.89

and if we want a direct comparison we can do that too!

describeBy(HR,group=data$CONDITION)

 Descriptive statistics by group 
group: 1
         vars  n  mean    sd median trimmed   mad  min    max range skew
HRBASE1     1 21 75.62 12.74   75.0   74.88  8.90 53.8 103.75 49.95 0.54
HRPREP1     2 21 83.17 13.58   81.0   82.75 16.31 58.0 109.67 51.67 0.24
HRTALK1     3 21 89.54 16.00   88.0   88.69 16.31 67.0 118.67 51.67 0.43
HRMATH1     4 21 81.12 15.19   77.3   79.46 13.39 59.3 120.33 61.03 0.94
HRRECOV1    5 21 72.90 11.79   72.3   72.19  8.90 56.8  95.25 38.45 0.43
HRBASE2     6 21 77.33 16.31   75.8   76.88 15.57 52.5 106.25 53.75 0.37
HRPREP2     7 21 81.00 15.66   80.3   80.61 21.20 55.7 106.33 50.63 0.24
HRTALK2     8 21 87.51 16.11   84.0   86.76 17.79 65.0 116.00 51.00 0.30
HRMATH2     9 21 81.08 14.57   81.3   80.61  9.79 54.0 110.33 56.33 0.30
HRRECOV2   10 21 73.71 11.74   72.0   73.06 11.12 54.0  99.00 45.00 0.51
         kurtosis   se
HRBASE1     -0.28 2.78
HRPREP1     -0.93 2.96
HRTALK1     -1.01 3.49
HRMATH1      0.31 3.31
HRRECOV1    -0.77 2.57
HRBASE2     -0.94 3.56
HRPREP2     -1.35 3.42
HRTALK2     -1.26 3.52
HRMATH2     -0.70 3.18
HRRECOV2    -0.49 2.56
------------------------------------------------------------ 
group: 2
         vars  n  mean    sd median trimmed   mad  min    max range  skew
HRBASE1     1 21 75.00 11.46  72.00   74.50 13.34 57.5  99.50 42.00  0.37
HRPREP1     2 21 82.03 12.16  84.00   82.80  5.93 49.0 105.00 56.00 -0.77
HRTALK1     3 21 88.89 14.31  90.00   90.02 10.38 58.0 111.00 53.00 -0.75
HRMATH1     4 21 80.88 10.57  82.30   81.85 11.42 54.7  97.00 42.30 -0.69
HRRECOV1    5 21 71.10  9.62  72.00   71.18 10.67 53.5  86.80 33.30 -0.06
HRBASE2     6 21 73.80 14.16  72.80   73.73 17.12 46.0  96.75 50.75  0.09
HRPREP2     7 21 80.32 14.43  81.70   80.63 15.86 49.0 102.00 53.00 -0.15
HRTALK2     8 21 85.05 14.99  82.33   84.47 11.37 55.0 116.00 61.00  0.38
HRMATH2     9 21 80.97 13.92  77.00   80.32  7.41 53.3 116.70 63.40  0.55
HRRECOV2   10 21 74.00 13.05  73.00   73.53 13.71 49.0 101.00 52.00  0.31
         kurtosis   se
HRBASE1     -1.06 2.50
HRPREP1      0.76 2.65
HRTALK1     -0.11 3.12
HRMATH1      0.07 2.31
HRRECOV1    -1.18 2.10
HRBASE2     -1.17 3.09
HRPREP2     -0.84 3.15
HRTALK2     -0.35 3.27
HRMATH2      0.32 3.04
HRRECOV2    -0.63 2.85

Keep in mind that probability isn’t about the observed statistics, but the unobservable parameters that give rise to those statistics! Point being, this describe() function just gives you clues as to what might be going on, but it’s really your knowledge of probability that makes this meaningful!

If we want correlations, we can select pairs of variables

cor(data$HRBASE1,data$HRBASE2)
[1] 0.7418303

or just get all correlations for all variables in a dataset

round(cor(HR),2)
         HRBASE1 HRPREP1 HRTALK1 HRMATH1 HRRECOV1 HRBASE2 HRPREP2 HRTALK2
HRBASE1     1.00    0.79    0.72    0.76     0.84    0.74    0.71    0.72
HRPREP1     0.79    1.00    0.86    0.78     0.75    0.70    0.78    0.82
HRTALK1     0.72    0.86    1.00    0.76     0.65    0.53    0.59    0.71
HRMATH1     0.76    0.78    0.76    1.00     0.81    0.54    0.62    0.70
HRRECOV1    0.84    0.75    0.65    0.81     1.00    0.76    0.75    0.76
HRBASE2     0.74    0.70    0.53    0.54     0.76    1.00    0.92    0.84
HRPREP2     0.71    0.78    0.59    0.62     0.75    0.92    1.00    0.89
HRTALK2     0.72    0.82    0.71    0.70     0.76    0.84    0.89    1.00
HRMATH2     0.81    0.79    0.70    0.75     0.82    0.88    0.88    0.92
HRRECOV2    0.80    0.72    0.59    0.62     0.83    0.91    0.86    0.84
         HRMATH2 HRRECOV2
HRBASE1     0.81     0.80
HRPREP1     0.79     0.72
HRTALK1     0.70     0.59
HRMATH1     0.75     0.62
HRRECOV1    0.82     0.83
HRBASE2     0.88     0.91
HRPREP2     0.88     0.86
HRTALK2     0.92     0.84
HRMATH2     1.00     0.92
HRRECOV2    0.92     1.00

Back to properties of variances and covariance, just to demonstrate a point, even if we don’t know the underlying distributions, these properties still work!

v1=var(data$HRBASE1)
v2=var(data$HRBASE2)
cov=cov(data$HRBASE1,data$HRBASE2)

v1+v2+2*cov
[1] 644.0034
var(data$HRBASE1+data$HRBASE2)
[1] 644.0034

A primary reason it is important to understand some basics of probability theory is that you will often encounter data that has different probabilistic properties, so we need to know how to think about it from the perspective of probability theory. Even if you don’t need to calculate specific probabilities, understanding the probabilistic underpinnings of data can change how you think about the data. To help think through possible distributions for a variable, I wrote the Plot_Dist() function. This will check your data for some basic information, and pop out an interactive widget to compare possible distributions. If your data have impossible values for a distribution (e.g., binomial data must be 0 or 1), it won’t list that as an option, so you can focus on only those distributions that are possible for your variable. It will give you a histogram so you can visually see the distribution, and the sample descriptive statistics. As you change the options, it will also give the implied density on the histogram and sample statistics assuming the distribution you select based on the theoretical properties from probability theory. This can help give a check on whether or not it makes sense to conceptualize a variable in one way or another!

A couple of notes on this. Because this is an interactive widget, this document can’t demonstrate its functionality. Below is a couple screenshots of what it will look like when you run the program. Additionally, this widget is powered by R shiny, which is a part of R to make fun pop outs like this. After you close the R Shiny pop out app, it will sometimes have a tiny stop sign in the top right of the console. If the stop sign is there, be sure to click on it when you are done! Otherwise, R will need a restart before you run more code!

X=rnbinom(n=100,size=3,prob=0.5)

Plot_Dist(X)

Plot_Dist(data$HRBASE1)

Heart Rate

Examining baseline heart rate, this one looks pretty normal to me. Technically isn’t because heart rate can’t be negative, but we’re far away from zero, so that is effectively an impossible scenario!

Plot_Dist(data$CortBase1)

Cortisol

Considering now basline cortisol, this one seems more exponential to me, since it’s a biomarker that can’t be less than zero and shows a lot of skew, more than any other distribution implies.

Finally, now that we’ve informed ourselves about the data some, we can move on to whatever else we wanted to do. But before doing that, we need to check for the stop sign. Here is where the stop sign would be located, if you need to click on it!

Stop Sign

Key Takeaways

  • Data can take many shapes and forms, and we shouldn’t assume they are always normal (more on where that belief comes from tomorrow)
  • The easiest way to get a sense of data is to examine the histogram and try to connect it to known probability distributions
  • You can calculate probabilities and simulate data using the d, p, q, and r functions
  • Be careful about transforming data, it may help, but it also changes the probability distribution! Whatever choices you make, just be sure to explain and justify them!

Topic 4: Hypothesis Testing

Learning Goals

The goal of a hypothesis test is to identify a claim you would like to invalidate, and use the data to decide whether or not you are confident enough to invalidate that claim. In other words, we are going make an assumption, the “null hypothesis”, which we think is probably not true based on our understanding of the scientific context, but would like to evaluate whether or not we have enough evidence to say that original assumption really was a bad assumption. If our sample of data are so inconsistent with that null assumption, then we will conclude it probably was a bad assumption, in which case we reject the null hypothesis in favor of a different interpretation–one that is more consistent with what we originally thought was likely occurring informed by the scientific context. And with a foundation in probability theory, we can calculate a specific probability relating the assumed null hypothesis to our sample of data. Assuming that null hypothesis represents the true probability distribution, how likely is it we would ever obtain such a statistic from our observed sample? If it isn’t very likely (probability < 0.05 is the convention!), then that assumption probably wasn’t a good assumption, we can reject that null hypothesis! This doesn’t PROVE anything, it just gives us some evidence of which assumptions are more appropriate than others. More importantly, it is your ability to identify a meaningful null hypothesis that makes this valuable. You can pick any number for your null hypothesis, but that does not necessarily mean the the analysis is consistent with your scientific hypothesis! The extent to which there is congruence between the null hypothesis and relevance to your theory formulated as a testable hypothesis, that will determine how meaningful the test is!

Binomial example

Let’s get into an example. We’ll use a classic example as a starting point, testing if a coin is biased. Statisticians love to use this example because there’s just two events, the coin is heads or tails. And we care because if we’re using this coin in the Super Bowl, well we better make darn sure it’s fair or else there will be some very mad fans! So let’s assume the coin IS biased, so to say the probability of heads is not 50% but actually 60%! So our null hypothesis is assuming that coin flips follow a binomial distribution with 50% probability of heads. And this is a meaningful null hypothesis because if it isn’t 50%, we probably should get a different coin for the Super Bowl. To test this, we’ll flip the coin a bunch of times, say 100 times. And if it’s 50% probability, we’d expect to see 50 of the flips to be heads and 50 tails. But we wouldn’t be surprised if it was 49 or 51, that’s randomness! By calculating the specific probability of observing the number of heads we observe across all 100 coin flips will help us know if our sample statistic (the number of heads) is really that surprising. And if it is, probably shouldn’t assume 50% probability, and probably should get a new coin!

true_probability=0.6
null_probability=0.5

Simulating 100 random coin flips

flips=rbinom(100,size=1,prob=true_probability) #Cheat coin example
flips
  [1] 1 0 1 0 1 1 1 1 0 0 1 1 1 0 1 1 1 0 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1 1
 [38] 0 1 0 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0 0 1 0 1 0 0 1
 [75] 1 0 1 1 0 1 0 0 1 1 0 1 1 0 1 1 0 1 1 0 1 0 0 0 0 1

So we can calculate the probability of seeing our sample statistic number of heads OR MORE assuming the null is TRUE.

1-pbinom(q=sum(flips),size=100,prob=null_probability)
[1] 0.00331856

The pbinom() function calculates the cumulative probability of a binomial distribution. The q statement represents the number of events, the sum total number of simulated heads; the size is 100 because we flipped the coin 100 times; and the probability is our predefined null probability of 50%. Mathematically, this returns the probability of observing this many heads or fewer. In this case, we actually want to know if we will see this many heads or more (indicating a bias towards heads). So we need to subtract this probability from 1 to get the final p value.

NOTE: if you run the above code yourself, you will likely get a different result! To get the same result, set a random number seed, which will ensure the same result every time!

set.seed(999)
flips=rbinom(100,size=1,prob=true_probability) #Cheat coin example
sum(flips)
[1] 61
1-pbinom(q=sum(flips),size=100,prob=null_probability)
[1] 0.01048937

So we saw 61 heads values, and there’s only about a 1% chance that you’d get 61 heads or more if you flip the coin 100 times and it has 50% probability of heads. So putting it together, it seems like we probably shouldn’t assume the coin has a 50% probability of being heads–and we probably shouldn’t use this coin in the Super Bowl!

If we want, we can make a chart of this to show the probabilities visually! Starting by giving the probability of each value

x=0:100
y=dbinom(x,size=100,prob=null_probability)

and plotting it with some graphics for where our sample was, to visually identify if our statistic was especially likely!

plot(x=x,y=y,type="l",
     main="Probability of Heads Assuming 50% Probability",
     xlab="Number of Heads",
     ylab="Probability")
abline(v=sum(flips),col="blue")
polygon(c(x[x>=sum(flips)], 100, sum(flips)),
        c(y[x>=sum(flips)], 0, 0),
        col="blue",border=NA)
legend("topleft",
       legend="p(observed|null)",
       col=c("blue"),
       lty=1)

Pretty small chance of observing this many heads, we should get another coin!

Normal example

In a lot of applied research settings, you can get by pretty well with a normal distribution! That’s the idea, even if individual variables may not always follow a normal distribution, our estimates of the averages follow something pretty close to a normal distribution with some magnitude of precision. This generalization comes from the central limit theorem. So we could identify up front what magnitudes of association or group differences would be scientifically meaningful, and then use the normal distribution as a streamlined approach to test these statistics. We can test the probability of any numeric value, but in many cases, a null hypothesis of zero often is appropriate, meaning that we are testing the assumption of no difference or no association.

Starting with an example, we’ll use IQ scores again because their calculation is designed around the normal distribution. Let’s say that we have a psychiatric condition that tends toward higher IQ scores but has a lot of variation person to person! IQ scores follow a normal distribution with mean 100 and standard deviation 15, but let’s say people with this this neurological condition tend to have high IQ scores with mean 115 and standard deviation 30.

true_mean=115
true_SD=30

And setting up our null assumptions based on the manipulated mean and SD of IQ.

null_mean=100
null_SD=15

We can now simulate 50 random scores

set.seed(999)
scores=rnorm(50,true_mean,true_SD)

and calculate the probability of observing our SAMPLE MEAN assuming the NULL MEAN!

max(scores)
[1] 186.4799
min(scores)
[1] 51.58789
mean(scores)
[1] 107.2699
t=(mean(scores)-100)/(sd(scores)/sqrt(50))
1-pt(q=t,df=50-1)
[1] 0.04484663

Like with the coin, pt gives us the cumulative probability, this time based on a normal distribution with unknown variance (t distribution), testing the probability of the average score we saw in our sample assuming the null hypothesized mean of 100. The precision of our estimate of the mean is based on the standard deviation of the observed scores divided by the square root of the sample size, so it scales precision to how variable our sample was and how much data we collected. And we need to subtract this probability from one so we have the probability of our observed sample mean or a greater sample mean.

Looks like the group with the neurological condition had higher IQ scores in general (max of 186!), but they also had some low lows (min of 52), and the average was just a bit higher because of the variation in scores (107 as opposed to 100). But when we account for the variation in scores and the sample size, seems like there is some evidence the average is slightly higher for the patients with the neurological condition! Because when we assume the average was 100, it wasn’t very likely we’d see an average of 107 or higher, only happening about four and a half percent of the time! So it seems more credible that the patients with the neurological condition probably have a slightly higher IQ on average, even if their IQ scores have a much wider range!

Let’s sketch out the probabilities of our assumed null IQ scores and our observed scores

x=70:130
y1=dnorm(x,null_mean,null_SD)
y2=dnorm(x,mean(scores),sd(scores)/sqrt(50))

and now we can make a plot of them both, to identify how likely our sample mean is assuming the null mean!

plot(x=x,y=y2,type="l",
     main="Distribution of IQ Scores",
     xlab="Score",
     ylab="Probability",
     ylim=c(0,0.1),
     col="red")
lines(x=x,y=y1)
abline(v=null_mean,col="blue")
polygon(c(70,x[x<=null_mean], null_mean),
        c(0,y2[x<=null_mean],0),
        col="blue",border=NA)
legend("topleft",legend=c("Standardized IQ Scores",
                          "Estimated Sample IQ Mean",
                          "p(observed mean|null mean)"),
       col=c("black","red","blue"),
       lty=c(1,1,1))

This helps to give an intuitive distinction of how our observed sample compared to the null assumption of how IQ scores are distributed–seems reasonably to conclude out sample had higher IQ scores on average!

Taking hypothesis testing to regression (Y = Mx + b)

Here’s an example I’ve been working on. We’re looking at how often enteral feed tubes get infected and need to be replaced. And let’s say that younger kids are less likely to have an infection. Older kids are more out and about, plus they have had a feed tube in longer, so the tubes may be in worse condition and just get infected more often for older kids. We want to conceptualize this as Y = Mx + b, so we’ll have Y be the number of infections in some period of time and x be how old the child is. Then, using a regression model, we’ll estimate the most likely value of M, the magnitude of association between age and infections. We’ll also get an estimate for b, the Y intercept. We aren’t too interested in that right now, we’ll talk more about that in the next sessions.

First let’s simulate some data, starting with ages. Let’s say in our data collection young kids are on average 10 years old with standard deviation 2 years, and older kids are on average 14 also with standard deviation 2 years. And let’s say we simulate collecting data on 40 kids (20 younger, 20 older).

set.seed(999)
younger_age=rnorm(20,10,2)
older_age=rnorm(20,14,2)

Always nice to have a plot of our sample data

x=seq(2,20,length=100)
y1=dnorm(x,10,2)
y2=dnorm(x,14,2)

plot(x=x,y=y1,type="l",
     main="Distribution of Ages",
     xlab="Age",
     ylab="Probability")
lines(x=x,y=y2,col="red")
legend("topright",
       legend=c("Younger","Older"),
       col=c("black","red"),
       lty=c(1,1))

Now we’ll do the same thing, but this time with number of infections. Since you can’t have a partial infection, I’ll assume these follow a Poisson distribution for counts. And we’ll make sure younger kids have fewer infections appointments (on average 2) than older kids (on average 5)

set.seed(999)
younger_infection=rpois(20,2)
older_infection=rpois(20,5)

And making another chart so we can take a look at what the hypothetical histograms would look like if we collected data.

x=0:10
y1=dpois(x,2)
y2=dnorm(x,5)

plot(x=x,y=y2,type="l",
     main="Distribution of Infection Rates",
     xlab="Infections",
     ylab="Probability",col="red")
lines(x=x,y=y1)
legend("topright",
       legend=c("Younger","Older"),
       col=c("black","red"),
       lty=c(1,1))

Now that we have some simulated data, we can combine this into one dataset

data=cbind(c(younger_infection,older_infection),  #Infection rates (Y)
           c(younger_age,older_age))              #Ages (x)
data=data.frame(data)
colnames(data)=c("Infections","Age")
data
   Infections       Age
1           1  9.436520
2           2  7.374881
3           0 11.590368
4           3 10.540141
5           3  9.445387
6           0  8.867953
7           2  6.242683
8           0  7.466418
9           1  8.064501
10          2  7.757981
11          1 12.650927
12          2 10.267955
13          0 11.877499
14          6 10.345076
15          0 11.915301
16          3  7.274628
17          1 10.136670
18          3 10.201315
19          0 11.802690
20          0  5.851286
21          8 11.542873
22          6 15.286089
23          5 13.280474
24          4 14.588071
25          7 11.749463
26          7 15.284531
27          5 11.786525
28          6 12.230319
29          7 10.891810
30          5 13.746642
31          2 18.765328
32          3 15.202552
33          5 14.358723
34          5 16.161063
35          5 13.506376
36          8  9.772526
37          7 13.258945
38          7 15.045736
39          1 15.035611
40          4 11.194978

which can allow us to compare the two traits

plot(data$Infections~data$Age,
        main="Infection Rate by Age",
        xlab="Age",
        ylab="Infections")

and we can see visually some association. Now getting more specific, we can use regression analysis, which is just fancy version of connect the dots, using calculus to infer the most likely value of the slope coefficient M representing the association between age and infections; and the Y intercept b:

mod=lm(data$Infections~data$Age)
summary(mod)

Call:
lm(formula = data$Infections ~ data$Age)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.7846 -1.7932  0.0403  1.3883  5.1542 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)  -0.3478     1.5800  -0.220   0.8269  
data$Age      0.3268     0.1327   2.463   0.0184 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.447 on 38 degrees of freedom
Multiple R-squared:  0.1377,    Adjusted R-squared:  0.115 
F-statistic: 6.066 on 1 and 38 DF,  p-value: 0.01843

The provided model object gives an an automated p value testing the assumption the coefficient is zero. That may or may not actually test your scientific hypothesis, so just be careful in interpreting those! In this case, the null assumption was reasonably that age is not associated with infections, numerically testing an assumption of 0 slope coefficient, and sufficient evidence to reject the null will help us focus our resources on who to screen for infections. The p value, representing the probability that we would see our observed association assuming a zero relationship, is small, 0.0148. Conventionally, we would view this as significant, hence the star next to it. This means there is evidence to support that older children had more infections on average, the null assumption of no relationship probably was a bad idea. So we reject the null, and conclude there is evidence that we should be more worried for older children with enteral feed tubes.

Key Takeaways

  • Theory provides the context to a research question
  • A specific scientific hypothesis comes from theory, a meaningful finding that would inform your opinion
  • A testable hypothesis is implied by a scientific hypothesis, a specific numeric value (difference in group averages, magnitude of association) that can be tested as different from a chosen value
  • The null hypothesis is a number you assume but hope to reject by testing its probability in a sample of data
  • The null hypothesis can be any number for any distribution, however in this program we will generally design applications where we are testing a null of zero in a normal distribution, to streamline hypothesis testing
  • The p value is the probability of observing your sample statistic assuming the null, so the probability of observing your group difference or association assuming there is no difference or no association
  • Importantly, the p value is only meaningful because of the theory that grounds the scientific hypothesis, the accuracy in specifying the testable hypothesis, and the relevance of the null hypothesis to the testable hypothesis
  • Anything else is would be unclear how to interpret or what conclusions to draw

Topic 5: Continuous X, Normal Y

Learning Goals

We’ll go over some examples estimating linear associations for continuous X variables! This is the most direct equivalent of Y = Mx + b. Importantly, because the slope parameter and intercept parameter are estimates that we can reasonably assume follow a normal distribution (average at the true value, with some estimates above or below), we can use probability theory to test whether or not these are meaningfully different from a hypothesized value (often zero)!

As always, we need to start with reading the data in!

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

Heart Rate and Stress Response

  • Theory: Some people just have a higher heart rate in response to stress because different people are sensitive to stress in different ways, and this may pose a threat to detecting differences attributable to the experimental gratitude condition
  • Scientific hypothesis: Participants with higher heart rate while preparing for the speech stage of protocol at time 1 will also have higher heart rate while preparing for the speech stage at time 2 two weeks later
  • Testable hypothesis: The association between time 1 speech stage heart rate and time 2 speech stage heart rate will be positive
  • Null hypothesis: We will assume there is no association between time 1 and time 2 speech stage heart rates, numerically a value of zero
  • Threat to validity: Not fully accounting for other context that has change (i.e., two weeks of gratitude condition or control condition!)
  • Threat to validity: A practice effect (i.e., having been through this protocol once before) may be more salient than individual uniqueness

Always nice to start with a plot!

plot(x=data$HRPREP1,y=data$HRPREP2,
     main="Heart Rate during Speech Prep by Protocol",
     xlab="First Prep",
     ylab="Second Prep")

Visualy, sure looks like there’s an association, but we’ll want to test that more carefully to back it up with statistics! Unless we have a zombie in the dataset, we aren’t anticipating anybody to have zero heart rate! So we will start by centering the data at the sample average so we can more meaningfully interpret the intercept, which is just the average when the X variable is equal to zero. We’ll also square the data to think about a curvilinear relationship!

data$Prep1_c=data$HRPREP1-mean(data$HRPREP1)
data$Prep1_c2=data$Prep1_c^2

Let’s start by estimating the two models, for linear and curvillinear relationships

mod1=lm(HRPREP2~Prep1_c,data=data)
mod2=lm(HRPREP2~Prep1_c+Prep1_c2,data=data)

At this point, we might be tempted to take a look at the model results, because everybody’s waiting on that p value! But we aren’t quite ready yet, because if the model doesn’t meet some assumptions, then the p value may not be reliable! This is important because nothing’s more disappointing than having a significant p value, but later learning it’s a bad model! If you start by checking the assumnptions first, you don’t get your hopes up too early!

So what assumptions are we worried about? We are assuming the errors are normally distributed with mean zero. What does that mean? That means our estimates aren’t systematically above or below observed scores, they are equally likely to be above or below without skew or discrepancies in variance. We’ll never know that for certain, because we only have our sample of data, but we can check for problems by plotting the residuals, which just means how far off our predictions were! Additionally, we may like to know if the extra curvilinear relationship actually did anything to help out. All of this is summarized using the inspect_mods() function using the functions provided.

The inspect_mods() function provides a couple pices of output, first is some plots of how well out model did at making accurate predictions. First, it will create a histogram of the residuals, which should look like a bell curve with an average at zero, meaning no systematic bias equally likely to be above or below the observed data. It will also create a Q-Q plot. The idea of a Q-Q plot is like taking the normal distribution bell curve, but pulling at the ends until the bell shape becomes one straight line. Specifically, we will plot each observed residual (how far off our model prediction was from the observed score) ordered from smallest to largest based on where we would expect each value to be if the residuals are truly normal. If our predictions are unbiased, then it will be a straight line up across the diagonal. If there is bias, then the residuals will veer off from the line. This gives us a visual check of how well the model did.

While pictures are the most insightful, these are always a bit interpretive, so it might be nice to have some numeric information to directly compare the models with a bit more precision. The inspect_mods() function will also create a table with some model fit statistics that do just this. First, it presents the AIC (Akaike information criterion), BIC (Bayesian information criterion), and -2 log likelihood. These statistics all represent the same idea as the histogram of residuals Q-Q plot, but it turns it into a number based on an assigned probability assuming a normal distribution. See the slideshows for additional information on what distinguishes these metrics and why, but the interpretation is simple. If the number is further left on the number line (i.e., closer to zero; or in the cases where the value is less than zero, more negative), then the model is doing a better job of predicting the observed data. Put another way, when the Q-Q plot is more straight on the diagonal, the values of the AIC, BIC, and -2LL will all be further left on the number line, which can help numerically compare two models especially when the Q-Q plot and histogram of residuals may look fairly similar.

Marginal R2 is doing the same goal of trying to assign a numeric value to predictive accuracy, but it is accomplished in a much simpler way. Here, the correlation between observed scores and predicted scores is estimated and squared. This metric is often interpreted as representing how much percentage of variation is explained by the model coefficients as a proportion of total variation in the outcome variable. I find that definition highly conceptual, even if mathematically justified under many assumptions. But there is an intuitive reason this approach makes sense. If the model is making accurate predictions, then the correlation will be very large, close to 1.0, the highest possible value for a correlation, resulting in an R2 value that is also very large. If the model is doing a poor job of making accurate predictions, then the correlation will be small, close to zero, resulting in an R2 that is also very small. This is why I like this metric, whether or not it always represents a percentage of variation explained, it does make good sense for why it would be helpful to identify which model was more accurate in making predictions.

inspect_mods(mod=list(mod1,mod2),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2        Interpretation
Parameters        2       3     Smaller is better
AIC          311.23  313.17     Smaller is better
BIC          316.45  320.12     Smaller is better
-2LL         305.23  305.17     Smaller is better
Marginal R2    0.61    0.61 Closer to 1 is better

Residuals look appropriate and don’t appear to show systematic bias. The number lines at the top are provided as a reminder for how to interpret AIC, BIC, -2LL, and marginal R2. Comparing the linear and curvillinear modles, the curvillinear model didn’t seem to make much of a difference and model fit was generally about the same or slightly worse (i.e., further right on the number line for AIC and BIC), so the linear seems appropriate!

At this point, I’m pretty sure the quadratic relationship didn’t do much for us, but we can do inference on the coefficients to check our expectations so far! This will test the probability that each coefficient is equal to zero.

summary(mod1)

Call:
lm(formula = HRPREP2 ~ Prep1_c, data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-20.5881  -5.3906   0.4308   7.2749  18.8871 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  80.6619     1.4482  55.696  < 2e-16 ***
Prep1_c       0.9125     0.1150   7.935 9.68e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 9.386 on 40 degrees of freedom
Multiple R-squared:  0.6115,    Adjusted R-squared:  0.6018 
F-statistic: 62.97 on 1 and 40 DF,  p-value: 9.679e-10
summary(mod2)

Call:
lm(formula = HRPREP2 ~ Prep1_c + Prep1_c2, data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-20.4042  -5.3386   0.1247   7.1251  19.1382 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 80.412453   1.780070  45.174  < 2e-16 ***
Prep1_c      0.916190   0.117310   7.810  1.7e-09 ***
Prep1_c2     0.001573   0.006371   0.247    0.806    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 9.498 on 39 degrees of freedom
Multiple R-squared:  0.6121,    Adjusted R-squared:  0.5922 
F-statistic: 30.78 on 2 and 39 DF,  p-value: 9.534e-09

As expected, that quadratic term isn’t adding much of anything, we don’t have evidence it is meaningfully different from zero, we probably don’t need it in here!

So we think the linear relationship makes sense and has some evidence in the data, terrific! But your scientific hypothesis may be more focused to compare two specific groups, rather than just looking at an overall association. While modeling heart rate as a continuum has better fidelity to the data and will give more accurate estimates and p values, we can still use the model to estimate averages implied for any level of heart rate. For example, suppose our scientific hypothesis wanted to compare the time 2 heart rate for people with low heart rate in the first protocol (the “cool cucumbers”) and people who had high heart rate in the first protocol (the “worriers”). First we can estimate the heart rate for these two groups at time 2. Second, we can formulate a testable hypothesis that people who were 10 BPM below average at time 1 will have a lower heart rate at time 2 than people who were 10 BPM above average at time 1. The null hypothesis is that there is no difference between these two groups. Evidence of a difference, sufficient evidence to reject the null hypothesis of no difference, would demonstrate how some people have a high heart rate and other people have a low heart rate. This may be a more refined scientific hypothesis than an overall association, and it can also help with science communication, because some people find group averages more concrete than the concept of association, even if they are mathematically equivalent.

To do this, we will need to set up the linear combination matrix, or L matrix. This just means choosing values for each coefficient that would represent the averages we are interested in estimateing. Let’s start with the “cool cucumbers”. That will mean the intercept gets a 1 because this is included with all estimates of the mean, and -10 for heart rate at first protocol!

L_low=c(1,-10)

And then we can do it again for the “worriers”, but they will get a 10 for heart rate at time 1 because that’s the comparison we wanted to make!

L_high=c(1,10)

We can combine these two estimates into one L matrix using cbind()

L=cbind(L_low,L_high)

and finally extract the model implied estimates using the Est_Mod() function!

(NOTE: mod is the model you want to create implied estimates for. L is the L matrix of implied group averages, and make sure each estimate has as many inputs as parameters in the model! Est_Names is the names for each estimate. To compare groups, diff lets you compare any two groups, just specify the column numbers from the L matrix, in this case 1 and 2 since there’s only two estimates. Plot creates charts for whatever groups you want to chart, again based on the column numbers in the L matrix, in this case 1 and 2 since there’s only two columns. ylab allows you to specify a label for the Y axis, and main allows you to specify a title for the whole chart.)

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=c("Cool Cucumbers","Worriers"),
            diff=c(1,2),
            plot=c(1,2),
            ylab="Preparation Heart Rate",
            main="Preparation Heart Rate between Worriers and Cool Cucumbers")
                            
 Input L Matrix of Estimates
            Cool Cucumbers Worriers
(Intercept)              1        1
Prep1_c                -10       10
                    Cool Cucumbers Worriers
Point Estimate               71.54    89.79
Standard Error                1.85     1.85
95 % CI Lower Limit          67.80    86.05
95 % CI Upper Limit          75.27    93.52
                                                                                 
 Difference between Cool Cucumbers and Worriers = -18.25, t(40) = 7.94, p < 0.001

As we could infer from the association coefficient, people with low heart rate at the first protocol had significantly lower heart rate at the second protocol compared to people with high heart rate at the first protocol, supporting the scientific hypothesis. Importantly, by using the L matrix to inform conclusions, we can tie these differences to average heart rate levels, which might have more meaningful interpretive value than an abstract concept of assocition!

Before feeling completely confident in these final conclusions, there’s one last analysis diagnostic check we can perform ! A concern is, what if there’s a few cases in the data that have really wild data, people who are very sensitive to stress or completely oblivious to it. Or alternatively, maybe for somebody the heart rate device wasn’t attached correctly, so their data are inconsistently recorded? No histogram is perfectly normal and no Q-Q plot forms a completely straight line, so how can we know if it’s one or two individuals who are screwing up the model for everybody else? In general, I’d be cautious about labeling anybody an outlier unless you had corroborating evidence an error was made, but it is a valid worry that we can provide a quick investigation of using the df_L() function. This function goes through the model and assumes everybody has “outlier potential”. The function goes through everybody and systematically removes them from the model once, using everybody else left in the dataset to estimate the model again. Then, it records the values of the new estimates based on the L matrix you provide, the estimates off of which you want to draw conclusions. It will compare the values of the new estimates to the values of the old estimates. If they don’t change much, or if they are at least symmetric suggesting equal likelihood of increasing or decreasing the estimates for each individual in the dataset, that supports that the model is reliable and not unduly influenced by a handful of people. If the estimates demosntrate one or two individuals are greatly increasing or decreasing the values of the averages, that is cause for concern that the sample is unreliable. Again, we can’t say these individuals are outliers unless you have additional reason to think an error was made. But sometimes errors are made, even innocuous problems (e.g., if there’s missing data coded as -999 you forgot to remove), and this can help make sure your final conclusions are reliable!

h=df_L(mod=mod1,
       L=L,
       Est_Names=c("Cool Cucumbers","Worriers"))
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Cool Cucumbers Worriers
Biggest Increases                        
1 (+)                         28       33
2 (+)                          8        8
3 (+)                         24       36
4 (+)                         37       40
5 (+)                         29        1
Biggest Decreases                        
1 (-)                         30       15
2 (-)                         34       34
3 (-)                          7       20
4 (-)                         18       18
5 (-)                         32       10

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.584
                          

Visually, looks like no one individual is influencing the estimates of these averages that much, which helps feel more confident in the conclusions we are drawing–no one individual changed the estimates of the averages by much more than half of a percentage of what was implied the model with everybody included! Additionally, leave one out R2 puts a statistic on model reliability interpreted the same way as marginal R2 based on how well the estimated models predict data that were left out of the model A value of 0.584 is pretty large, supporting that this is a reliable model that explains a significant proportion of variation in heart rate scores!

At this point, scientifically, I would probably stop here! There’s clear evidence for the magnitudes of association we wanted to compare, and we can tie it to specific average heart rate levels with a chart of results. But, for demonstration purposes, let’s do it again for the quadratic model, just to show what it would look like! The only real difference here is that we need to update the L matrix, because the linear model only had two parameters (intercept, linear age relationship), whereas the quadratic model has three parameters (intercept, linear change, quadratic change). This isn’t hard to do, since the quadratic term is just the linear value squared we just need to square it!

L=cbind(c(1,-10,(-10)^2), #Cool cucumbers
        c(1,10,(10)^2))   #Worriers

Now that we have the L matrix set up, this would be the best time to check the reliability of the estimates made, before we look at any p values! You don’t want to be in the position where the p value for your hypothesis is only significant when the model is making bad predictions, so safest to run all diagnostic checks before you look at your final p values!

h=df_L(mod=mod2,
       L=L,
       Est_Names=c("Cool Cucumbers","Worriers"))
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Cool Cucumbers Worriers
Biggest Increases                        
1 (+)                         28       33
2 (+)                          8        8
3 (+)                         24       36
4 (+)                         29       40
5 (+)                         33        1
Biggest Decreases                        
1 (-)                         30       15
2 (-)                         34       34
3 (-)                         18       20
4 (-)                          7       18
5 (-)                         32       10

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.576
                          

Same story here as before! The model with the quadratic coefficient was slightly less reliable, but still no one individual changes the estimated mean by more than one percent, which is pretty small! Additionally, leave one out R2 is just about the same as before, so both models are highly consistent!

Now we run the Est_Mod() function again this time using the quadratic model, which we had called m2!

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=c("Cool Cucumbers","Worriers"),
            diff=c(1,2),
            plot=c(1,2),
            ylab="Preparation Heart Rate",
            main="Preparation Heart Rate between Worriers and Cool Cucumbers")
                            
 Input L Matrix of Estimates
            Cool Cucumbers Worriers
(Intercept)              1        1
Prep1_c                -10       10
Prep1_c2               100      100
                    Cool Cucumbers Worriers
Point Estimate               71.41    89.73
Standard Error                1.94     1.88
95 % CI Lower Limit          67.48    85.92
95 % CI Upper Limit          75.34    93.54
                                                                                 
 Difference between Cool Cucumbers and Worriers = -18.32, t(39) = 7.81, p < 0.001

Pretty much the same deal as before, but that isn’t surprising given that we didn’t find much evidence of a quadratic relationship when we inspected the raw regression output! Importantly, this gives us the opportunity to compare these conceptual groups accounting for the continuous nature of hear rate, and allow for the possibility of a non-linear relationship between traits–even if we didn’t find much evidence that the relationship was anything but linear!

Key Takeaways

  • Linear regression is just a fancy version of Y = Mx + b
  • Sometimes you need to make it curvillinear if a straight line doesn’t make sense for your understanding of the scientific theory
  • The raw model coefficients test the probability that each is equal to zero, but that isn’t always directly meaningful
  • Picking meaningful group averages to compare can be a much simpler way to understand the results, especially when raw model coefficients aren’t clearly interpretable
  • To estimate the average for a group, just recreate what their x data would look like and use Est_Mod() to give the model implied estimated averages
  • Comparisons can easily be made as well using the same Est_Mod() function, to compare and test magnitudes of difference between any chosen groups

Topic 6: Categorical X, Normal Y

Learning Goals

This time, we’ll be looking at how to do group difference comparisons. This still conceptually represents Y = Mx + b, the only difference is that x only assumes values of 0 and 1. We can still draw a line between points at 0 and 1, that just means the slope of the line no longer represents “magnitude of association” or “degree of tilt” like it did before, but now it represents the average difference between a specified “reference group” at 0 and a comparison group at 1 represented by that x dummy code!

Always starting the same, reading the data in

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

Two group comparison

  • Theory: Like discussed before, gratitude will change perspective on stress, and because of it participants who practiced gratitude will not experience as big of a change in heart rate in response to stress
  • Scientific hypothesis: Participants practicing gratitude will have less of a spike in heart rate at recovery compared to baseline
  • Testable hypothesis: Modeling the change in heart rate from baseline to recovery, the parameter representing group difference attributable to participants in the gratitude condition will be negative (meaning less increase in heart rate)
  • Null hypothesis: We will assume there is no difference between gratitude and control conditions, the difference parameter is zero
  • Threat to validity: Some people have different personal responsiveness to stress, which may be more relevant than the gratitude practice
  • Threat to validity: College students may not generalize well to most people, especially for topics like stress responsiveness!

First, let’s process our gratitude variable to be more clear

data$group=ifelse(data$CONDITION==1,"Gratitude","Control")

and now we’ll specify control the reference level

data$group=as.factor(data$group)
data=within(data, group<-relevel(data$group,ref="Control"))

I know this blurb of code is ugly! Think of it this way:

dataset_name=within(dataset_name, Categorical<-relevel(dataset_name$Categorical,ref=“Reference”))

You’d need to edit the bolded sections to be your dataset name, categorical variable within the dataset, and specific level you want to be the reference. The rest of the code you can leave as is.

Now let’s create a variable for the CHANGE in heart rate relative to baseline during the second protocol, which can address the concern that some people came in with a higher heart rate just because of whatever was going on during the day rather than the stress task itself.

data$delta_HR=data$HRRECOV2-data$HRBASE2

Taking a look at the data

plot(data$delta_HR~data$group,
     main="Recovery Heart Rate by Experimental Condition",
     xlab="Experimental Condition",
     ylab="Change in Recovery Heart Rate from Baseline")

Visually, sure looks like gratitude was better off than control, but we’ll need to evaluate that more rigorously with regression analysis! Now, just like before, we’ll estimate the model, check residuals, and extract some macro level output on how well the model fit the data

mod=lm(delta_HR~group,data=data)

inspect_mods(mod=mod,
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
             Model        Interpretation
Parameters       2     Smaller is better
AIC         277.78     Smaller is better
BIC            283     Smaller is better
-2LL        271.78     Smaller is better
Marginal R2   0.09 Closer to 1 is better

So it does look like we have some skew in residuals, we tend to overestimate the magnitude of change a bit. We should just be careful, that might mean that some people benefited differently from the gratitude intervention, so we should be cautious in drawing conclusions!

summary(mod)

Call:
lm(formula = delta_HR ~ group, data = data)

Residuals:
    Min      1Q  Median      3Q     Max 
-16.183  -3.430   1.556   4.704   8.317 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)  
(Intercept)      0.2048     1.3753   0.149   0.8824  
groupGratitude  -3.8214     1.9450  -1.965   0.0564 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.303 on 40 degrees of freedom
Multiple R-squared:  0.08801,   Adjusted R-squared:  0.06521 
F-statistic:  3.86 on 1 and 40 DF,  p-value: 0.05642

That gives us some idea, seems like some support for the hypothesis that the gratitude condition will have less of a spike in heart rate (p = 0.0564, so not quite enough evidence to reject the null hypothesis of no difference, but it’s clearly on the boarder). But what this won’t tell us is the average change for each group, which would seem to be a more intuitive way to tell this story! To get the model implied average change for each group we can use the L matrix!

#Control (intercept only, because it is the reference group)
L_ctrl=c(1,0)
#Gratitude (intercept plus difference statistic)
L_grat=c(1,1)

#Putting them in one matrix
L=cbind(L_ctrl,
        L_grat)

Additionally, this can help us calibrate the magnitude of concern we had about those residuals that were a bit skewed!

h=df_L(mod=mod,
       L=L,
       Est_Names=c("Control condition","Gratitude condition"))
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Control condition Gratitude condition
Biggest Increases                                      
1 (+)                            22                  13
2 (+)                            29                  36
3 (+)                            34                  28
4 (+)                            18                  42
5 (+)                             6                  25
Biggest Decreases                                      
1 (-)                            40                  31
2 (-)                            33                   9
3 (-)                            26                   7
4 (-)                            39                  15
5 (-)                            14                  23

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                         
  Leave One Out R2 = 0.02
                         

Looks like our estimate of the average for the control condition is less reliable than that of the gratitude, but it does not appear to be unduly influenced by a handful of individuals! This is encouraging, because we would like to conclude the gratitude group benefited more, so it helps to see that that estimate is more reliable!

We can finally take a look at the implied averages using the Est_Mod() function

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=c("Control condition","Gratitude condition"),
            diff=c(1,2),
            plot=c(1,2),
            ylab="Change in Recovery Heart Rate from Baseline",
            main="Change in Heart Rate by Experimental Condition")
                            
 Input L Matrix of Estimates
               Control condition Gratitude condition
(Intercept)                    1                   1
groupGratitude                 0                   1
                    Control condition Gratitude condition
Point Estimate                   0.20               -3.62
Standard Error                   1.38                1.38
95 % CI Lower Limit             -2.57               -6.40
95 % CI Upper Limit              2.98               -0.84
                                                                                              
 Difference between Control condition and Gratitude condition = 3.82, t(40) = 1.96, p =  0.056

So this tells us that on average, the control condition had almost no change from baseline to recovery, on average just 0.20 beats per minute, and the confidence interval and plot shows us it’s a wide estimate! But for the gratitude group, heart rate decreased from baseline to recovery, by 3.62 beats per minute on average! Further, the confidence interval (and the plot of the change statistic that includes the confidence interval visually) excludes a value of zero, suggesting that people in the gratitude condition decreased significantly from baseline to recovery! That’s interesting, because we originally anticipated that heart rate levels would spike at recovery, but it seems by then heart rate levels were about the same or decreased on average! At the bottom we have the difference between groups, which has the same p value as we had in the summary(mod) statement, just outside of significant at p = 0.056. This may be because of the model residuals, a more complex model may give a better estimate of this difference! Regardless, this provides some support of the testable hypothesis that participants who practiced gratitude would have lower heart rates than the control group did each relative to baseline levels. Importantly, it is inconsistent with the testable hypothesis, because it seems to have been by way of actually lower heart rates at recovery for the gratitude group, rather than higher heart rates for the control group! This is informative for the theory of how gratitude shapes perceptions of stressful events, and physiological stress reactions.

More than two groups comparison

  • Theory: Gratitude will shape the way stressful events are perceived, but it depends on actually practicing gratitude
  • Scientific hypothesis: Participants with partial adherence to the gratitude protocol will not show decreases in heart rate compared to the control group, but participants with full adherence to the gratitude protocol will show decreases in heart rate compared to control
  • Testable hypothesis: The heart rate difference parameter for the participants who completed all 14 days of the gratitude protocol will be will be positive when comparing to the control group, but not the heart rate difference parameter for participants who showed partial completion.
  • Null hypothesis: The heart rate averages are all the same, no difference, numerically zero
  • Threat to validity: People who do not adhere to the gratitude protocol may not like or benefit from gratitude, and that may be the reason they do not adhere to the protocol
  • Threat to validity: This is essentially a revision to the previous analysis. You need to be careful with too much tinkering with analysis after it’s completed!

First we’ll need to set up our groups! If a person was in the control group, consider them control. If they are in the gratitude group and had less than 14 days of adherence, consider them partial adherence.

data$Exposure=ifelse(data$group=="Control","Control",
                     ifelse(data$DAYSOFUSINGAPP<14,"Partial","Full"))
data$Exposure=as.factor(data$Exposure)
data=within(data, Exposure<-relevel(data$Exposure,ref="Control"))

table(data$Exposure)

Control    Full Partial 
     21      15       6 

Plotting data

plot(data$delta_HR~data$Exposure,
     main="Recovery Heart Rate by Gratitude Exposure",
     xlab="Group",
     ylab="Change in Recovery Heart Rate from Baseline")

Visually, sure seems like the partial group didn’t show the same decreases in heart rate as the full group! Fitting model and checking out diagnostics

mod=lm(delta_HR~Exposure,data=data)

inspect_mods(mod=mod,
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
             Model        Interpretation
Parameters       3     Smaller is better
AIC         279.24     Smaller is better
BIC         286.19     Smaller is better
-2LL        271.24     Smaller is better
Marginal R2    0.1 Closer to 1 is better

Visually, it’s clear we aren’t doing a great job characterizing the heart rates of these students. Marginal R2 is okay though, at 0.1, which can be interpreted as meaning we only explained 10% of the variance. We can examine the model in detail to get more specific information.

summary(mod)

Call:
lm(formula = delta_HR ~ Exposure, data = data)

Residuals:
    Min      1Q  Median      3Q     Max 
-15.560  -3.430   1.468   4.745   8.740 

Coefficients:
                Estimate Std. Error t value Pr(>|t|)  
(Intercept)       0.2048     1.3839   0.148   0.8831  
ExposureFull     -4.4448     2.1439  -2.073   0.0448 *
ExposurePartial  -2.2631     2.9357  -0.771   0.4454  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.342 on 39 degrees of freedom
Multiple R-squared:  0.09972,   Adjusted R-squared:  0.05355 
F-statistic:  2.16 on 2 and 39 DF,  p-value: 0.1289

So far looking better, now the gratitude group is significantly different from the control group! Also, we thought the partial group wouldn’t have as large of a difference compared to control, and that is demonstrated, their difference is not significant! Using the L matrix, we can get the implied average changes in heart rate, which may tell this story more intuitively. Additionally, we can evaluate the reliability of the model results and ensure that one individual isn’t limiting the quality of the model solution using the df_L() function. Lastly, the L matrix can allow us to test a difference between full and partial completion of the gratitude protocol, which could tell us if the partial completion was significantly less decrease in heart rate than the full completion.

L=cbind(c(1,0,0), #Control Group, intercept only because reference
        c(1,1,0), #Full completion of gratitude, intercept plus difference coefficient
        c(1,0,1)) #Partial completion of gratitude, intercept plus difference coefficient
h=df_L(mod=mod,
       L=L,
       Est_Names=c("Control",
                   "Full",
                   "Partial"))
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Control Full   Partial
Biggest Increases                       
1 (+)                  22   13        28
2 (+)                  29   36        41
3 (+)                  34   42 5, 16, 35
4 (+)                  18   25 5, 16, 35
5 (+)                   6    5 5, 16, 35
Biggest Decreases                       
1 (-)                  40    9        31
2 (-)                  33    7        38
3 (-)                  26   15        32
4 (-)                  39   23         3
5 (-)                  14   17         1

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.008
                          

It appears as if the model the control group is a lot more variable than the gratitude groups, but it doesn’t look like one individual is to blame! At this point we can use the Est_Mod() function to plot the group averages and test differences!

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=c("Control",
                        "Full",
                        "Partial"),
            diff=c(2,3),
            plot=c(1,2,3),
            ylab="Change in Recovery Heart Rate from Baseline",
            main="Change in Heart Rate by Experimental Condition")
                            
 Input L Matrix of Estimates
                Control Full Partial
(Intercept)           1    1       1
ExposureFull          0    1       0
ExposurePartial       0    0       1
                    Control  Full Partial
Point Estimate         0.20 -4.24   -2.06
Standard Error         1.38  1.64    2.59
95 % CI Lower Limit   -2.59 -7.55   -7.30
95 % CI Upper Limit    3.00 -0.93    3.18
                                                                      
 Difference between Full and Partial = -2.18, t(39) = 0.71, p =  0.481

We saw before that the gratitude group showed significant decreases in heart rate from baseline, as indicated by the confidence interval excluding a value of zero. This time, the partial completion group does not exclude a value of zero, so it seems the benefits of gratitude were exclusive to those who completed the full gratitude protocol. Additionally, before the difference between gratitude and control groups wasn’t quite significant. Now, as we could see from the model results, the difference between full completers and the control group is significant. The difference between the partial completers and the control group is not significant, as was anticipated. Keep in mind that this could be because of the sample size on the partial completion group, which was only six participants. But it is consistent with the hypothesis that gratitude is a benefit so long as you actually practice it!

Key Takeaways

  • The intercept in regression analysis represents the average when all other variables are numerically equal to zero
  • For categorical groups, that means the average for a chosen reference group
  • Each coefficient represents the difference between the specified reference group and the other group listed
  • A more intuitive reporting of results can be accomplished by adding the intercept plus difference coefficients, to represent the group averages rather than differences relative to the reference group
  • Model implied group averages and testing of any two selected groups can be accomplished using the L matrix and the Est_Mod() function

Topic 7: Multiple Regression Analysis

Learning Goals

Today we’ll be talking about how to specify an analysis accounting for more than one variable. You can include as many variables as you like, but keep in mind the more complex it gets, the more opportunity there is for problems that you never notice! Less is more, your ability to craft hypotheses around the specific variables you include, and their interactions especially, that helps identify a more nuanced result! We’ll do an example of each possible form of interaction.

Packages used:

  • Ray’s functions
source("https://raw.githubusercontent.com/JoshuaRayTanzer/Functions/main/Functions.R")

Getting the data loaded for today

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

Categorical Categorical Comparison

  • Theory: Men are sometimes less comfortable socially expressing gratitude, so benefits of gratitude may be limited to female participants
  • Scientific hypothesis: Women in the gratitude condition will show larger decreases in heart rate from baseline to recovery relative to men in the gratitude condition
  • Testable hypothesis: Using the L matrix to estimate the mean difference in heart rate for men in the gratitude condition and women in the gratitude condition, the difference will be negative, suggesting women had larger decreases
  • Null hypothesis: We will assume no difference between men and women in the gratitude condition, numerically zero difference
  • Threat to validity: This sample is of college students at a progressive leaning liberal arts school, so the machismo that underpins the hypothesis may not be as strong for this specific group of men
  • Threat to validity: Men are less represented in this sample, so power may not be enough

Processing the data (this should look familiar so I won’t go into detail)

#Making clearer labels
data$group=ifelse(data$CONDITION==1,"Gratitude","Control")
data$Gender_Label=ifelse(data$GENDER==1,"Male","Female")

#Reference level specification
data$group=as.factor(data$group)
data=within(data, group<-relevel(data$group,ref="Gratitude"))

data$Gender_Label=as.factor(data$Gender_Label)
data=within(data, Gender_Label<-relevel(data$Gender_Label,ref="Female"))

table(data$group,data$Gender_Label)
           
            Female Male
  Gratitude     15    6
  Control       17    4
#Creating change in heart rate scores
data$delta_HR=data$HRRECOV2-data$HRBASE2

We can use one string of text to make multiple charts, just separate the X variables with an asterisk (*)!

plot(data$delta_HR~data$group*data$Gender_Label,
     main="Recovery Heart Rate by Geneder and Experimental Condition",
     xlab="Gender Group or Experimental Condition",
     ylab="Change in Recovery Heart Rate")

Visually, looks like the difference is larger based on gratitude and control than gender, however these charts don’t tell us much about the interaction! We can use the usual model estimation code, we just need to specify an interaction with the asterisk, like the plot code! Then it’s back to the usual diagnostic checks before looking into inferential tests

mod=lm(delta_HR~group*Gender_Label,data=data)

inspect_mods(mod=mod,
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
             Model        Interpretation
Parameters       4     Smaller is better
AIC         278.85     Smaller is better
BIC         287.54     Smaller is better
-2LL        268.85     Smaller is better
Marginal R2   0.15 Closer to 1 is better

Residuals aren’t perfect, some skew, but we’ve seen worse! Also it’s suggesting we explained 15% of the variance, which by conventions in research is pretty good! And now checking out the model

summary(mod)

Call:
lm(formula = delta_HR ~ group * Gender_Label, data = data)

Residuals:
    Min      1Q  Median      3Q     Max 
-15.270  -3.853   1.452   3.905   9.030 

Coefficients:
                              Estimate Std. Error t value Pr(>|t|)   
(Intercept)                     -4.530      1.612  -2.810   0.0078 **
groupControl                     5.577      2.212   2.521   0.0160 * 
Gender_LabelMale                 3.197      3.016   1.060   0.2959   
groupControl:Gender_LabelMale   -7.619      4.598  -1.657   0.1058   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.245 on 38 degrees of freedom
Multiple R-squared:  0.1495,    Adjusted R-squared:  0.08234 
F-statistic: 2.226 on 3 and 38 DF,  p-value: 0.1009

Really what we’re interested in is the specific groups, to compare women and men in the gratitude condition! We could do that by mental math, by trying to add up those coefficients in our head, but that’d be easy to make a mistake! L matrix to the rescue!

Before, it was pretty easy to just write this by hand, but as you add more variables in, it starts to get a little more complicated. To help make sure we set up the L matrix properly, I set up some tools to simplify the process.

The L_Specify() function will pull up an interactive widget to help simplify L matrix creation. If you give it the model and the number of estimates you want to create, it will pull out the coefficients and create a table so you can easily type in what values for each x to estimate the average of Y. To further simplify things, if you specify Type=“Mean”, you will only need to specify the x levels, and not worry about the intercept or proper specification of the interactions! When you have finished filling in the table, click “Display Backup Code”. This will print out a line of code you can copy and paste into R to save your work!

We’ll make four estimates, for each of male and female participants in gratitude and control conditions. Since these are all categorical, all we need are dummy codes, numerically 1 for the averages for male participants and 0 for female participants; and numerically 1 for the control condition, and 0 for gratitude!

L_Specify(mod=mod,
          Est_Num=4,
          type="Mean")
#Copying and pasting the output backup code
L=cbind(c(1, 0, 0, 0),
        c(1, 1, 0, 0),
        c(1, 0, 1, 0),
        c(1, 1, 1, 1))

Est_Names=c('Female, Grat', 'Female, Ctrl', 'Male, Grat', 'Male, Ctrl')

Because this was created by an interactive widget, I can’t demonstrate it here. But here is a screenshot of what the final table should look like! At the top, you can give a name for each estimate to keep organized. Then in each subsequent row, you can plug in the numbers for each x variable you want to use in each estimate. The L matrix isn’t so bad right now with two categorical variables, but it can get more complicated if you have more variables or continuous variables. This helps you keep your thoughts organized in one place and make sure the interactions are specified correctly!

Finished Table

Now that we’ve got the L matrix figured out, we can use df_L() to evaluate how reliable these estimates are, especially since there was some skew in the residuals!

h=df_L(mod=mod,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Female, Grat Female, Ctrl Male, Grat         Male, Ctrl
Biggest Increases                                                        
1 (+)                       13           22         28                 40
2 (+)                       36           29          1                 39
3 (+)                       42        6, 18         15 14, 20, 24, 26, 33
4 (+)                       25        6, 18     30, 38 14, 20, 24, 26, 33
5 (+)                        5           20     30, 38 14, 20, 24, 26, 33
Biggest Decreases                                                        
1 (-)                        9           33         31                 34
2 (-)                       15           26          7                 10
3 (-)                       38           14         23                  1
4 (-)                       32            8         17                  5
5 (-)                    3, 30           24     16, 22                 13

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.014
                          

It does look like our estimates for male participants are much less consistent, but that’s surely because we had a very small sample of male participants! Fortunately, the influence is fairly symmetric, so at least we don’t have one individual unduly influencing the average for this group!

At this point, it’s right back to the Est_Mod() function to get model implied averages for each group! First, we’ll run it to get the plot of all four groups. Because our hypothesis was focused on comparing women and men in the gratitude condition, we’ll compare estimates 3 and 4, which directly tests that scientific hypothesis that men in the gratitude condition will not benefit from the gratitude condition compared to women in the gratitude condition against the null hypothesis of no difference! We can run the code a second time to accomplish that, and by adding Print_L=F, it will only provide the estimates and the test of difference without the visual clutter of the L matrix which we already have in the first bit of code!

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4),
            ylab="Change in Recovery Heart Rate",
            main="Change in Heart Rate by Experimental Condition and Gender Identity")
                            
 Input L Matrix of Estimates
                              Female, Grat Female, Ctrl Male, Grat Male, Ctrl
(Intercept)                              1            1          1          1
groupControl                             0            1          0          1
Gender_LabelMale                         0            0          1          1
groupControl:Gender_LabelMale            0            0          0          1
                    Female, Grat Female, Ctrl Male, Grat Male, Ctrl
Point Estimate             -4.53         1.05      -1.33      -3.37
Standard Error              1.61         1.51       2.55       3.12
95 % CI Lower Limit        -7.79        -2.02      -6.49      -9.70
95 % CI Upper Limit        -1.27         4.11       3.83       2.95

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=Est_Names,
            diff=c(3,4),
            Print_L=F)
                    Female, Grat Female, Ctrl Male, Grat Male, Ctrl
Point Estimate             -4.53         1.05      -1.33      -3.37
Standard Error              1.61         1.51       2.55       3.12
95 % CI Lower Limit        -7.79        -2.02      -6.49      -9.70
95 % CI Upper Limit        -1.27         4.11       3.83       2.95
                                                                              
 Difference between Male, Grat and Male, Ctrl = 2.04, t(38) = 0.51, p =  0.615

So this would appear to be partial support for the scientific hypothesis. As we can see from the chart and confidence intervals, women in the gratitude condition showed significant decreases in heart rate from baseline to recovery, because the change change statistic excludes a value of zero. Also consistent with the hypothesis, there wasn’t evidence men in the gratitude condition improved, with a distinctly smaller decrease in heart rate and a confidence interval that can’t exclude a zero change in heart rate. So it would appear men did not benefit from the gratitude condition, as was the concern. However, when we test the specific hypothesis that men benefited less than women, we can’t reject the null hypothesis of no difference. And the reason is pretty clear, men had a very imprecise estimate, probably because there weren’t very many men in the dataset! So the data are consistent with our hypothesis, but there isn’t quite enough evidence to feel confident in that conclusion, and collecting a larger sample would probably help!

Continuous Categorical Comparison

  • Theory: Gratitude changes the way a person perceives events, which will mean reduced stress response when posed with a challenge and greater subsequent happiness because of it
  • Scientific hypothesis: Participants in the gratitude condition will have lower heart rate during recovery compared to participants in the control condition regardless of baseline heart rate
  • Testable hypothesis: If we use the L matrix to estimate average heart rate for people in gratitude and control condition at high and low baseline heart rate levels, the differences between gratitude and control will be negative for each group
  • Null hypothesis: No differences between any groups will be demonstrated, numerically zero difference between all groups
  • Threat to validity: Some participants will have a higher heart rate at baseline, which may mask the hypothesized benefits of gratitude (will be addressed)
  • Threat to validity: Some participants will have a higher heart rate in general, which may mask the hypothesized benefits of gratitude (will not be addressed…but could be addressed with a more complex generalization of this model!)

Before we subtracted out the baseline heart rate, now we can just include it in the model! Data processing as usual!

data$group=ifelse(data$CONDITION==1,"Gratitude","Control")

#Specifying the reference levels
data$group=as.factor(data$group)
data=within(data, group<-relevel(data$group,ref="Gratitude"))

#Centering baseline heart rate at sample average, and allowing for a curvilinear trend
data$Base2_c=data$HRBASE2-mean(data$HRBASE2)
data$Base2_c2=data$Base2_c^2

Starting with a chart

plot(data$HRRECOV2~data$group*data$HRBASE2,
     main="Recovery Heart Rate by Baseline Heart Rate and Experimental Condition",
     xlab="Experimental Condition or Baseline Heart Rate",
     ylab="Recovery Heart Rate")

The association between baseline heart rate and recovery heart rate is obvious, but it’s less clear how gratitude and control come into play here–we’ll have to see! Same model statements, but this time we’ll have two models because we could look at baseline heart rate as a linear change or a quadratic change!

#Linear
mod1=lm(HRRECOV2~group*Base2_c,data=data)
#Quadratic
mod2=lm(HRRECOV2~group*Base2_c+group*Base2_c2,data=data)


inspect_mods(mod=list(mod1,mod2),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2        Interpretation
Parameters        4       6     Smaller is better
AIC          258.45  262.32     Smaller is better
BIC          267.14  274.49     Smaller is better
-2LL         248.45  248.32     Smaller is better
Marginal R2    0.85    0.85 Closer to 1 is better

All in all, residuals look pretty good! The histogram is a bit chunky rather than the smooth bell curve we hope to see, but the Q-Q plots line up around the diagonal pretty well! Also doesn’t look like the quadratic term did much, model fit is about the same or worse, but we can see if it’s meaningful in in the model output, when we test the assumption that the quadratic term is equal to zero!

summary(mod1)

Call:
lm(formula = HRRECOV2 ~ group * Base2_c, data = data)

Residuals:
   Min     1Q Median     3Q    Max 
-9.740 -3.310  1.031  3.254 10.914 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)          72.53152    1.07538  67.447  < 2e-16 ***
groupControl          2.96485    1.52234   1.948   0.0589 .  
Base2_c               0.66904    0.06715   9.963 3.78e-12 ***
groupControl:Base2_c  0.17740    0.10243   1.732   0.0914 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.898 on 38 degrees of freedom
Multiple R-squared:  0.8522,    Adjusted R-squared:  0.8405 
F-statistic: 73.02 on 3 and 38 DF,  p-value: 7.809e-16
summary(mod2)

Call:
lm(formula = HRRECOV2 ~ group * Base2_c + group * Base2_c2, data = data)

Residuals:
    Min      1Q  Median      3Q     Max 
-9.7409 -3.4833  0.7626  3.2255 11.1748 

Coefficients:
                        Estimate Std. Error t value Pr(>|t|)    
(Intercept)           72.4420619  1.4748592  49.118  < 2e-16 ***
groupControl           3.3953839  2.1395005   1.587    0.121    
Base2_c                0.6653560  0.0798047   8.337 6.31e-10 ***
Base2_c2               0.0003742  0.0040943   0.091    0.928    
groupControl:Base2_c   0.1770644  0.1132626   1.563    0.127    
groupControl:Base2_c2 -0.0021682  0.0070298  -0.308    0.760    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.025 on 36 degrees of freedom
Multiple R-squared:  0.8526,    Adjusted R-squared:  0.8321 
F-statistic: 41.65 on 5 and 36 DF,  p-value: 5.461e-14

Doesn’t look like that quadratic trend was helping, so we probably don’t need it. Reviewing the summary statement, does seem like there’s something going on with dynamic differences in the relationships between heart rate at baseline and gratitude condition! But it’s still unprocessed model output, this doesn’t really test our hypothesis yet. By looking at the specific groups with high and low heart rate levels, we can directly test the hypothesis that gratitude lowered heart rate! Ideally we’ll see that regardless of baseline heart rate level, gratitude condition participants will have lower heart rate on average. To define low and high heart rate, let’s look at participants with heart rate 10 beats per minute below average (“cool cucumbers”) and 10 beats per minute above average (“worriers”), numerically -10 and 10 respectively! As before, we can use the L_Specify() statement widget to keep organized

L_Specify(mod1,
          Est_Num=4,
          type="Mean")
#Copying and pasting the backup code
L=cbind(c(1, 0, 10, 0),
        c(1, 1, 10, 10),
        c(1, 0, -10, 0),
        c(1, 1, -10, -10))

Est_Names=c('Worrier, Grat', 'Worrier, Ctrl', 'Cool Cucumber, Grat', 'Cool Cucumber, Ctrl')

And this is what the widget should look like:

Finished Table

The last step before we get to examining the model estimated averages, we should check consistency of our estimates!

h=df_L(mod=mod1,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Worrier, Grat Worrier, Ctrl Cool Cucumber, Grat
Biggest Increases                                                
1 (+)                         1            22                  15
2 (+)                        42             6                   7
3 (+)                        38            24                  38
4 (+)                        19             4                  31
5 (+)                         3            29                   3
Biggest Decreases                                                
1 (-)                        13            33                  17
2 (-)                        28            40                   5
3 (-)                        36            26                  25
4 (-)                         5            39                  28
5 (-)                        25             8                   1
                  Cool Cucumber, Ctrl
Biggest Increases                    
1 (+)                              29
2 (+)                              34
3 (+)                              18
4 (+)                              20
5 (+)                              37
Biggest Decreases                    
1 (-)                              10
2 (-)                              14
3 (-)                              39
4 (-)                              26
5 (-)                              12

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.813
                          

This demonstrates strong reliability of the model, no individual impacted the final model estimates more than about one or two percent! Additionally, leave one out R2 suggests the model made fairly accurate predictions for just about everybody! And now we get back to comparing the groups with Est_Mod()! As before, we’ll want to run it a couple times. First we’ll create a plot of everything; then we’ll do diff=c(1,2) comparing gratitude and control groups for the worriers; then we’ll do it again with diff=c(3,4) to compare gratitude and control for the cool cucumbers!

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4),
            ylab="Recovery Heart Rate",
            main="Recovery Heart Rate by Baseline Heart Rate and Experimental Condition")
                            
 Input L Matrix of Estimates
                     Worrier, Grat Worrier, Ctrl Cool Cucumber, Grat
(Intercept)                      1             1                   1
groupControl                     0             1                   0
Base2_c                         10            10                 -10
groupControl:Base2_c             0            10                   0
                     Cool Cucumber, Ctrl
(Intercept)                            1
groupControl                           1
Base2_c                              -10
groupControl:Base2_c                 -10
                    Worrier, Grat Worrier, Ctrl Cool Cucumber, Grat
Point Estimate              79.22         83.96               65.84
Standard Error               1.20          1.40                1.33
95 % CI Lower Limit         76.79         81.12               63.15
95 % CI Upper Limit         81.66         86.80               68.53
                    Cool Cucumber, Ctrl
Point Estimate                    67.03
Standard Error                     1.24
95 % CI Lower Limit               64.51
95 % CI Upper Limit               69.55

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            diff=c(1,2),
            Print_L=F)
                    Worrier, Grat Worrier, Ctrl Cool Cucumber, Grat
Point Estimate              79.22         83.96               65.84
Standard Error               1.20          1.40                1.33
95 % CI Lower Limit         76.79         81.12               63.15
95 % CI Upper Limit         81.66         86.80               68.53
                    Cool Cucumber, Ctrl
Point Estimate                    67.03
Standard Error                     1.24
95 % CI Lower Limit               64.51
95 % CI Upper Limit               69.55
                                                                                     
 Difference between Worrier, Grat and Worrier, Ctrl = -4.74, t(38) = 2.56, p =  0.014
hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            diff=c(3,4),
            Print_L=F)
                    Worrier, Grat Worrier, Ctrl Cool Cucumber, Grat
Point Estimate              79.22         83.96               65.84
Standard Error               1.20          1.40                1.33
95 % CI Lower Limit         76.79         81.12               63.15
95 % CI Upper Limit         81.66         86.80               68.53
                    Cool Cucumber, Ctrl
Point Estimate                    67.03
Standard Error                     1.24
95 % CI Lower Limit               64.51
95 % CI Upper Limit               69.55
                                                                                                 
 Difference between Cool Cucumber, Grat and Cool Cucumber, Ctrl = -1.19, t(38) = 0.65, p =  0.517

Putting it all together, as we can see from the chart, the cool cucumbers were really cool cucumbers! Regardless of gratitude or control condition, they had very low heart rates at recovery! Against the scientific hypothesis, we do not have evidence to reject the null hypothesis that there is no difference between the groups, there was very little difference in heart rate between experimental conditions at recovery! Conversely, for the worriers, participants in the control condition had significantly higher heart rates at recovery compared to worriers in the gratitude condition. Putting it all together, this provides some support for the hypothesis, gratitude was a benefit, but only for participants who had a high baseline heart rate. This is important because it suggests while gratitude may help with managing life’s stressors, some people don’t need the help!

Continuous Continuous Comparison

To use an observational approach, we could compare participant heart rates at baseline to understand how stress responsiveness is different for different groups.

  • Theory: While going through a stressful experience may make anybody’s heart rate increase, the impact may be stronger for people who experience chronic stress and may have an already elevated heart rate
  • Scientific hypothesis: Participants with a high heart rate at baseline who demonstrate a large increase in heart rate during the math stress task will have the highest heart rate at recovery because they will not be able to relax following a stressful experience as quickly
  • Testable hypothesis: Using the L matrix to estimate the average heart rate at recovery for the four possible combinations of baseline heart rate (low or high) and change in heart rate (no change or increase), participants with a high heart rate at baseline and a large increase in heart rate during the stress task will show the highest heart rate at recovery, a positive difference compared to any other group
  • Null hypothesis: We will assume there are no differences or associations between heart rate changes over the duration of the protocol
  • Threat to validity: We are assuming high and low heart rate are attributable to personal psychology or health state, but it alternatively could represent whether or not participants took the stairs or the elevator (data collection was on the third floor)
  • Threat to validity: Changes in heart rate represent a physiological response to stress, but incorporating a subjective rating of stress during the task may be more relevant

As always, we need to start with some data processing!

#First X variable: heart rate at baseline, centered at the sample average
data$Base1_c=data$HRBASE1-mean(data$HRBASE1)
data$Base1_c2=data$Base1_c^2

#Second X variable: change in heart rate from baseline
data$delta_math=data$HRMATH1-data$HRBASE1
data$delta_math2=data$delta_math^2

Nice too to see how the data look

plot(data$HRRECOV1~data$HRBASE1*data$delta_math,
     main="Recovery Heart Rate by Base Heart Rate and Change in Math Heart Rate",
     xlab="Baseline Heart Rate or Change in Math Heart Rate",
     ylab="Recovery Heart Rate")

You can easily tell the relationship between baseline heart rate and recovery heart rate, but the spike in heart rate during the math task does not appear to be as obvious! Now we can set up our models, but we’ll have four this time (linear or quadratic for each continuous measure)!

mod1=lm(HRRECOV1~Base1_c*delta_math,data=data)
mod2=lm(HRRECOV1~Base1_c*delta_math+Base1_c2*delta_math,data=data)
mod3=lm(HRRECOV1~Base1_c*delta_math+Base1_c*delta_math2,data=data)
mod4=lm(HRRECOV1~Base1_c*delta_math+Base1_c2*delta_math+
          Base1_c2*delta_math2,data=data)

Taking a look at model residuals will help to identify which approach is most appropriate!

inspect_mods(mod=list(mod1,mod2,mod3,mod4),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2 Model 3 Model 4        Interpretation
Parameters        4       6       6       8     Smaller is better
AIC          261.43  262.36  263.77  266.21     Smaller is better
BIC          270.11  274.52  275.93  281.85     Smaller is better
-2LL         251.43  248.36  249.77  248.21     Smaller is better
Marginal R2    0.79     0.8     0.8    0.81 Closer to 1 is better

By the model fit statistics, it doesn’t appear the quadratic effects are adding much to the model. However, model 3 (quadratic change during the stress task, linear for the baseline heart rate) appears to have less skew in the residuals. Let’s take a look at model 1 and model 3 and compare to see if that quadratic trend is adding much as individual effect coefficients.

summary(mod1)

Call:
lm(formula = HRRECOV1 ~ Base1_c * delta_math, data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-11.5578  -3.0824  -0.1497   4.1248   9.5316 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        70.419276   0.987527  71.309  < 2e-16 ***
Base1_c             0.769787   0.077133   9.980 3.61e-12 ***
delta_math          0.313932   0.096085   3.267  0.00231 ** 
Base1_c:delta_math  0.008102   0.006839   1.185  0.24352    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.075 on 38 degrees of freedom
Multiple R-squared:  0.7902,    Adjusted R-squared:  0.7737 
F-statistic: 47.72 on 3 and 38 DF,  p-value: 5.825e-13
summary(mod3)

Call:
lm(formula = HRRECOV1 ~ Base1_c * delta_math + Base1_c * delta_math2, 
    data = data)

Residuals:
     Min       1Q   Median       3Q      Max 
-11.9162  -3.1123  -0.0998   3.6892  10.4857 

Coefficients:
                      Estimate Std. Error t value Pr(>|t|)    
(Intercept)         70.4416676  1.0093552  69.789  < 2e-16 ***
Base1_c              0.8035075  0.0844410   9.516  2.3e-11 ***
delta_math           0.2238143  0.1649550   1.357    0.183    
delta_math2          0.0065993  0.0092854   0.711    0.482    
Base1_c:delta_math   0.0190850  0.0114366   1.669    0.104    
Base1_c:delta_math2 -0.0007911  0.0006578  -1.203    0.237    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.112 on 36 degrees of freedom
Multiple R-squared:  0.7984,    Adjusted R-squared:  0.7704 
F-statistic: 28.51 on 5 and 36 DF,  p-value: 1.404e-11

At this point, it seems like model 1 makes most sense, so we’ll use that one going forward, because we don’t need extra effects in the model if they aren’t adding anything! But so far, the line by line list of coefficients hasn’t really tested the hypothesis. We hypothesized that participants with low heart rate at baseline who showed a large increase in heart rate during the math task would show the largest decrease in heart rate from baseline to recovery. To test this specifically, we’ll need to estimate the average change in heart rate statistics for these four groups! As we’ve used in the past, we’ll use a value of -10 to represent low baseline heart rate and 10 to represent high baseline heart rate. To identify people who increased heart rate in response to stress, we’ll use a value of 10 as well. For people who did not respond to stress, we’ll use a value of 0, representing that they didn’t meaningfully change heart rate during the stress protocol.

Like before, we can use the L_Specify() statement to keep organized!

L_Specify(mod=mod1,
          Est_Num=4,
          type="Mean")
#Backup code
L=cbind(c(1, -10, 0, 0),
        c(1, -10, 10, -100),
        c(1, 10, 0, 0),
        c(1, 10, 10, 100))

Est_Names=c('Low HR, No Stress', 'Low HR, Stress', 'High HR, No Stress', 'High HR, Stress')

Finished Table

So as we can see in the screenshot, values of -10 and 10 for the high and low baseline heart rate levels; and values of 0 and 10 for no response to stress and high response to stress.

Before we take a look at model implied averages, we can do one last diagnostic check with df_L() to consider reliability of our estimates!

h=df_L(mod=mod1,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Low HR, No Stress Low HR, Stress High HR, No Stress
Biggest Increases                                                    
1 (+)                            36             16                 24
2 (+)                            27             27                  1
3 (+)                             8             37                  3
4 (+)                             3             41                  4
5 (+)                            28              8                 19
Biggest Decreases                                                    
1 (-)                            18              5                 36
2 (-)                            12             10                 18
3 (-)                            39             14                  2
4 (-)                            31             31                 22
5 (-)                            23             29                 26
                  High HR, Stress
Biggest Increases                
1 (+)                           1
2 (+)                          33
3 (+)                           4
4 (+)                          30
5 (+)                          21
Biggest Decreases                
1 (-)                           2
2 (-)                          38
3 (-)                          10
4 (-)                          18
5 (-)                          20

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                         
  Leave One Out R2 = 0.75
                         

This is good to see, our estimates are only changing by about one percent for any one individual, and leave one out R2 is very high suggesting the results are quite reliable! Now we can proceed to our final inferences using Est_Mod()! Like before, we’ll start with a plot, then test the differences. Next, we’ll use the diff statement to make comparisons. We hypothesized that participants with a high baseline heart rate and demonstration of a stress response will have the highest recovery heart rate of anybody. That group is represented by group four, so we will test as follows: diff=c(1,4), diff=c(2,4), and diff=c(3,4).

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4),
            ylab="Recovery Heart Rate",
            main="Recovery Heart Rate by Base Heart Rate and Math Heart Rate")
                            
 Input L Matrix of Estimates
                   Low HR, No Stress Low HR, Stress High HR, No Stress
(Intercept)                        1              1                  1
Base1_c                          -10            -10                 10
delta_math                         0             10                  0
Base1_c:delta_math                 0           -100                  0
                   High HR, Stress
(Intercept)                      1
Base1_c                         10
delta_math                      10
Base1_c:delta_math             100
                    Low HR, No Stress Low HR, Stress High HR, No Stress
Point Estimate                  62.72          65.05              78.12
Standard Error                   1.39           1.08               1.09
95 % CI Lower Limit             59.90          62.87              75.90
95 % CI Upper Limit             65.55          67.23              80.33
                    High HR, Stress
Point Estimate                82.07
Standard Error                 1.25
95 % CI Lower Limit           79.54
95 % CI Upper Limit           84.60

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            diff=c(1,4),
            Print_L=F)
                    Low HR, No Stress Low HR, Stress High HR, No Stress
Point Estimate                  62.72          65.05              78.12
Standard Error                   1.39           1.08               1.09
95 % CI Lower Limit             59.90          62.87              75.90
95 % CI Upper Limit             65.55          67.23              80.33
                    High HR, Stress
Point Estimate                82.07
Standard Error                 1.25
95 % CI Lower Limit           79.54
95 % CI Upper Limit           84.60
                                                                                            
 Difference between Low HR, No Stress and High HR, Stress = -19.35, t(38) = 10.43, p < 0.001
hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            diff=c(2,4),
            Print_L=F)
                    Low HR, No Stress Low HR, Stress High HR, No Stress
Point Estimate                  62.72          65.05              78.12
Standard Error                   1.39           1.08               1.09
95 % CI Lower Limit             59.90          62.87              75.90
95 % CI Upper Limit             65.55          67.23              80.33
                    High HR, Stress
Point Estimate                82.07
Standard Error                 1.25
95 % CI Lower Limit           79.54
95 % CI Upper Limit           84.60
                                                                                         
 Difference between Low HR, Stress and High HR, Stress = -17.02, t(38) = 11.24, p < 0.001
hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            diff=c(3,4),
            Print_L=F)
                    Low HR, No Stress Low HR, Stress High HR, No Stress
Point Estimate                  62.72          65.05              78.12
Standard Error                   1.39           1.08               1.09
95 % CI Lower Limit             59.90          62.87              75.90
95 % CI Upper Limit             65.55          67.23              80.33
                    High HR, Stress
Point Estimate                82.07
Standard Error                 1.25
95 % CI Lower Limit           79.54
95 % CI Upper Limit           84.60
                                                                                           
 Difference between High HR, No Stress and High HR, Stress = -3.95, t(38) = 3.68, p < 0.001

Putting it all together, the chart shows fairly clearly how the participants who had a high baseline heart rate and a spike in heart rate during stress tended toward higher heart rates at recovery, consistent with the hypothesis that chronic stress would result in higher heart rates at recovery. This is concerning because it suggests the problem of chronic stress may exacerbate the problems of going through a specific stressful experience.

Key Takeaways

  • The raw model coefficients represent additive relationships so that the combinations of the x values multiplied by the estimated coefficients correspond with the averages of the Y values
  • The individual raw model coefficients test the probability that each coefficient is equal to zero, which may be the testable hypothesis
  • Depending on how the scientific hypothesis is formulated and how data are processed, the raw model coefficients run a risk of being out of alignment with the scientific hypothesis if not interpreted carefully
  • Using the L matrix to estimate the averages for relevant groups implied by the model is a practical solution, and proper definition of the L matrix can be accomplished using L_Specify()
  • By formulating a scientific hypothesis around clinically relevant group comparisons worth making, and specifying the model based on whether or not x variables are truly continuous or categorical, it is much simpler to identify a testable hypothesis against a null hypothesis of no difference

Topic 8: The Generalized Linear Model

Learning Goals

Up until now, we have focused on how to make comparisons in a normally distributed Y variable based on different traits of x variables (categorical or continuous). Today we will consider what to do when Y isn’t normally distributed! The individual distribution of Y as normal or not normal is important because if Y is not normal you may have bias in the residuals, which can result in bad estimates of group averages and invalidates interpretation of p values. Additionally, the normal model provides output in the form of additive differences (how much larger or smaller are two groups), but interpretationally it may be of interest to compare in terms of multiplicative differences (how many times larger or smaller; how many times as likely). This is easily accomplished by generalized regression! We will go through one example with a binary Y event (often called “logistic regression”), and then another example with a continuous but not normal Y event.

Packages used:

  • Ray’s functions
source("https://raw.githubusercontent.com/JoshuaRayTanzer/Functions/main/Functions.R")

First as always we start with getting the data in!

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

Logistic regression

  • Theory: Practicing gratitude changes the way individuals perceive stressful circumstance, resulting in lower heart rates following a stressful experience
  • Scientific hypothesis: Participants who practice gratitude will have a lower heart rate at recovery relative to baseline regardless of how much their heart rate changed during stress; participants in the control group will only have a lower heart rate at recovery if they did not demonstrate a spike in heart rate during the stress protocol
  • Testable hypothesis: Using the L matrix, the percentage of participants who showed decreases in heart rate between baseline and recovery stages will be larger for participants in the gratitude condition, an odds ratio greater than one, especially when comparing between participant who showed a large increase in heart rate from baseline to stress conditions
  • Null hypothesis: All participants will have similar percentages of increases and decreases in heart rate, numerically an odds ratio of one
  • Threat to validity: Regression toward the mean, differences may be attributable to chance (baseline or recovery being unexpectedly high or low) rather than the experimental condition
  • Threat to validity: Here we’re converting change in heart rate to a binary (increase from first recovery protocol or decrease from first recovery protocol), however we don’t need to convert it to a binary, we could just subtract the two and model it as normal! This is done for demonstration purposes, but is not recommended to convert a continuum into a binary unless the differences are clearly not normal!

First some data processing

#Y event, if increase 1; else 0
data$increase_recov=ifelse(data$HRRECOV2>data$HRBASE2,1,0)

#Gratitude and control groups
data$group=ifelse(data$CONDITION==1,"Gratitude","Control")

data$group=as.factor(data$group)
data=within(data, group<-relevel(data$group,ref="Gratitude"))

#Change in heart rate between baseline and stress condition, plus a quadratic option
data$delta_math=data$HRMATH2-data$HRBASE2
data$delta_math2=data$delta_math^2

Since binary data are all or nothing, 0 or 1, they don’t always make a clean chart, so we’ll need to do some additional data processing to make plots! We’ll just extract the average percentages so we can compare between groups. Comparing based on change in heart rate during stress, we can use the same plot functions we’ve used in the past. Just be prepared that the plot may look extreme, because the events are all or nothing, numerically 0 or 1! This is a limitation of binary data, and why it is generally preferable to have continuous data if possible!

#Just for the plot
grat_increase=mean(subset(data,data$group=="Gratitude")$increase_recov)
ctrl_increase=mean(subset(data,data$group=="Control")$increase_recov)

barplot(c(grat_increase,ctrl_increase),
        names.arg=c("Gratitude","Control"),
        ylim=c(0,1),
        main="Recovery Heart Rate by Experimental Condition",
        xlab="Experimental Condition",
        ylab="Recovery Heart Rate (% Increased)")

plot(data$increase_recov~data$delta_math,
     main="Recovery Heart Rate by Math Heart Rate",
     xlab="Math Heart Rate Increase",
     ylab="Recovery Heart Rate (% Increased)")

Intuitively, these charts match what we had hypothesized, but we don’t know yet how precise that differences are, or how relevant their interaction may be! To gain more information on this, we’ll need to fit some models! Since Y is binary, we’ll use family=“binomial”(link=“logit”) to tell R that this is a binary event we want to understand by modeling the log odds of event. Since change in heart rate is a continuum, we’ll need to compare a couple models, with an without a quadratic curvillinear change!

mod1=glm(increase_recov~group*delta_math,family="binomial"(link="logit"),data=data)
mod2=glm(increase_recov~group*delta_math+group*delta_math2,family="binomial"(link="logit"),data=data)

And now we can compare residuals and overall model fit

inspect_mods(mod=list(mod1,mod2),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2        Interpretation
Parameters        4       6     Smaller is better
AIC           50.71   54.31     Smaller is better
BIC           57.66   64.73     Smaller is better
-2LL          42.71   42.31     Smaller is better
Marginal R2    0.15    0.16 Closer to 1 is better

The histograms of residuals may look a bit weird, that’s because the data are binary, which can result in what look like residuals that are more like two normal distributions (clustered around the 0s and 1s) rather than one single normal distribution. This is not preferred, but it does happen in practice. Fortunately, the Q-Q plots have closer match between expected and observed residuals, which helps instill confidence even if the other plots are a bit lop sided!

In this case, the quadratic trend doesn’t seem to do much better by model fit statistics, but the residuals look a little more even. That said, the quadratic coefficient seems to be largely influenced by one individual, so that is cause for concern!

summary(mod1)

Call:
glm(formula = increase_recov ~ group * delta_math, family = binomial(link = "logit"), 
    data = data)

Coefficients:
                        Estimate Std. Error z value Pr(>|z|)  
(Intercept)             -1.50737    0.72662  -2.074   0.0380 *
groupControl             0.68093    1.04479   0.652   0.5146  
delta_math               0.17383    0.09708   1.791   0.0734 .
groupControl:delta_math  0.04189    0.13677   0.306   0.7594  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 58.129  on 41  degrees of freedom
Residual deviance: 42.710  on 38  degrees of freedom
AIC: 50.71

Number of Fisher Scoring iterations: 4

Looks like there might be something going on among patients who showed a spike in math heart rate, but this doesn’t really represent a test of our hypothesis yet! To do that, we’ll need the L matrix! Like before, we can keep track of it all using L_Specify(). In this case, we’ll have gratitude (0) and control (1); as well as increased in heart rate (10 for the linear effect and 102 = 100 for the quadratic) and did not change heart rate (0 for linear and quadratic, because 02 = 0).

L_Specify(mod=mod1,
          Est_Num=4,
          type="Mean")
#Saving our work
L=cbind(c(1, 0, 10, 0),
        c(1, 1, 10, 10),
        c(1, 0, 0, 0),
        c(1, 1, 0, 0))

Est_Names=c('1. Grat, Increased HR', '2. Ctrl, Increased HR', '3. Grat, No Change in HR', '4. Ctrl, No Change in HR')

Finished Table

Before making the final interpretation, we should make sure that the estimates aren’t excessively impacted by a few individual data points!

h=df_L(mod=mod1,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Grat, Increased HR 2. Ctrl, Increased HR
Biggest Increases                                            
1 (+)                                 9                    12
2 (+)                                31                    16
3 (+)                                15                    35
4 (+)                                23                 6, 29
5 (+)                                38                 6, 29
Biggest Decreases                                            
1 (-)                                 5                    10
2 (-)                                30                    14
3 (-)                                21                     8
4 (-)                                41                    40
5 (-)                                42                    26
                  3. Grat, No Change in HR 4. Ctrl, No Change in HR
Biggest Increases                                                  
1 (+)                                    3                       40
2 (+)                                   32                        8
3 (+)                                   42                       26
4 (+)                                   19                       24
5 (+)                                   25                       33
Biggest Decreases                                                  
1 (-)                                    7                       27
2 (-)                                   17                        4
3 (-)                                   23                       35
4 (-)                                   15                       10
5 (-)                                   31                       12

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.192
                          

No enormous spikes, suggesting results do no depend on one individual changing the estimates for everybody else, and the estimates are fairly reliable per leave one out R2. Now we can get back to comparing between gratitude and control using Est_Mod()! First, we’ll make the plots; then we’ll run it with diff=c(1,2) comparing gratitude and control groups for people who increased in heart rate during the stress task (hypothesized to be a larger difference); and finally with diff=c(3,4) to compare gratitude and control for the people who didn’t show meaningful change during the stress task! Also, because this was a generalized model with a logit link, we need to add link=“Logit” to the function so that it will reverse transform log odds into estimated percentages; as well as transforming a difference in the log odds into an odds ratio per the diff statement!

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            link="Logit",
            plot=c(1,2,3,4),
            ylab="Recovery Heart Rate (% Increased)",
            main="Recovery Heart Rate by Experimental Condition and Change in Heart Rate During Stress")
                            
 Input L Matrix of Estimates
                        1. Grat, Increased HR 2. Ctrl, Increased HR
(Intercept)                                 1                     1
groupControl                                0                     1
delta_math                                 10                    10
groupControl:delta_math                     0                    10
                        3. Grat, No Change in HR 4. Ctrl, No Change in HR
(Intercept)                                    1                        1
groupControl                                   0                        1
delta_math                                     0                        0
groupControl:delta_math                        0                        0
                    1. Grat, Increased HR 2. Ctrl, Increased HR
Point Estimate                       0.56                  0.79
95 % CI Lower Limit                  0.24                  0.48
95 % CI Upper Limit                  0.84                  0.94
                    3. Grat, No Change in HR 4. Ctrl, No Change in HR
Point Estimate                          0.18                     0.30
95 % CI Lower Limit                     0.05                     0.09
95 % CI Upper Limit                     0.49                     0.67

hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            link="Logit",
            diff=c(1,2),
            Print_L=F)
                    1. Grat, Increased HR 2. Ctrl, Increased HR
Point Estimate                       0.56                  0.79
95 % CI Lower Limit                  0.24                  0.48
95 % CI Upper Limit                  0.84                  0.94
                    3. Grat, No Change in HR 4. Ctrl, No Change in HR
Point Estimate                          0.18                     0.30
95 % CI Lower Limit                     0.05                     0.09
95 % CI Upper Limit                     0.49                     0.67
                                                                                          
 Ratio of 1. Grat, Increased HR and 2. Ctrl, Increased HR = 0.33, t(38) = 1.11, p =  0.274
hat=Est_Mod(mod=mod1,
            L=L,
            Est_Names=Est_Names,
            link="Logit",
            diff=c(3,4),
            Print_L=F)
                    1. Grat, Increased HR 2. Ctrl, Increased HR
Point Estimate                       0.56                  0.79
95 % CI Lower Limit                  0.24                  0.48
95 % CI Upper Limit                  0.84                  0.94
                    3. Grat, No Change in HR 4. Ctrl, No Change in HR
Point Estimate                          0.18                     0.30
95 % CI Lower Limit                     0.05                     0.09
95 % CI Upper Limit                     0.49                     0.67
                                                                                                
 Ratio of 3. Grat, No Change in HR and 4. Ctrl, No Change in HR = 0.51, t(38) = 0.65, p =  0.518

As we can see by the charts, people who increased in heart rate during the stress task were more likely to increase in heart rate from baseline to recovery, which may be because they are simply sensitive to stress. But when comparing between gratitude and control, our hypothesis, while participants who practiced gratitude were on average less likely to have an increase in heart rate, it wasn’t a large enough difference to reject the null hypothesis of no difference. A larger sample size may help, or a model that accounts for more traits. But as is, we do not currently have evidence that gratitude made a difference!

Log based regression

  • Theory: Practicing gratitude can help people reframe stressful circumstances, which can result in reduced expression of stress hormone cortisol following a stressful event
  • Scientific hypothesis: Participants who practice gratitude will have less cotrisol released following the stress task relative to the control group, but differences will be largest for participants who release high levels cortisol to begin with
  • Testable hypothesis: Using the L matrix, the rate of cortisol secretion will be lower for participants in the control group, a rate ratio less than one, particularly for participants who demonstrated high cortisol release during the first protocol
  • Null hypothesis: All participants will have similar rates of cortisol, numerically an rate ratio of one
  • Threat to validity: If the gratitude condition is working and gratitude impacts cortisol release, participants in the gratitude condition will have lower cortisol prior to the stress task

As always we’ll start with some data processing and chart making!

#We could consider a linear and quadratic trend
#(No need to transform the outcome, that will be the link function)
data$Cort_Stress_c=data$CortStress1-mean(data$CortStress1)
data$Cort_Stress_c2=data$Cort_Stress_c^2

plot(data$CortStress2~data$CortStress1*data$group,
     main="Stress Cortisol by Experimental Condition",
     xlab="Baseline Cortisol or Experimental Condition",
     ylab="Stress Cortisol",
     log="xy")

Looks like the gratitude group has a bit lower cortisol levels, but the more striking difference is the clear association with first protocol cortisol levels! Let’s also try to understand the Y outcome in detail! Intuitively, I know that cortisol is a continuum, so I could think about this as a normal distribution. However, a normal distribution assumes the data are bell shaped and can be any numeric value. I know cortisol can’t be less than zero, and because of that you sometimes see a bunch of people with a lot of low values bunched up near zero and a few really big values! This sounds to me like an exponential distribution might make sense, since we often discuss biomarker excretion as an exponential process. But you never know with data, that’s why the best practice is to look at the histogram visually! This can be accomplished using the Plot_Dist() function, which will help inform us as to what kind of distribution makes sense (e.g., if it is safe to assume a normal distribution; if it isn’t normal, but it also isn’t exponential)! Because this is an interactive widget, I cannot present what the output would look like here, however here is a screen shot assuming my intuition, an exponential distribution.

Plot_Dist(data$CortStress2)

Exponential Distribution

Clearly there’s a lot of skew here, so a normal distribution probably isn’t the best choice. We could plausibly consider gamma/exponential distributions (gamma is a generalization of the exponential distribution), or a log normal (assuming the log of the data is normal). Putting this together with the different contingencies for modeling the X variable first protocol cortisol (linear or quadratic), that means there’s four possible models we could consider (linear or qudaratic association of first protocol cortisol; log normal and gamma/exponential distribution for second protocol cortisol)! That would be a lot to look at one at a time, but fortunately this is the real value of the inspect_mods() function, which can summarize all of the different models and directly compare model fit!

#Fitting the models
mod1=glm(CortStress2~group*Cort_Stress_c,family="Gamma"(link="log"),data=data)#Linear
mod2=glm(CortStress2~group*Cort_Stress_c+group*Cort_Stress_c2,
         family="Gamma"(link="log"),data=data)#Quadratic
#Log normal
mod3=glm(CortStress2~group*Cort_Stress_c,family="gaussian"(link="log"),data=data)#Linear
mod4=glm(CortStress2~group*Cort_Stress_c+group*Cort_Stress_c2,
         family="gaussian"(link="log"),data=data)#Quadratic

inspect_mods(mod=list(mod1,mod2,mod3,mod4),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2 Model 3 Model 4        Interpretation
Parameters        4       6       4       6     Smaller is better
AIC          -58.52  -71.22  -31.85  -41.74     Smaller is better
BIC          -49.83  -59.06  -23.16  -29.58     Smaller is better
-2LL         -68.52  -85.22  -41.85  -55.74     Smaller is better
Marginal R2    0.02    0.05    0.28    0.48 Closer to 1 is better

Clearly the gamma/exponential models are doing better with residuals, so we will focus on those. Even if the log normal has better “predictive accuracy” per marginal R2, if the residuals are bad nothing else matters! Additionally, the AIC, BIC, and -2LL are all smaller (i.e., more negative), which supports that the gamma/exponential model is truly doing a better job at representing the distribution of the data, even if the predictive validity of marginal R2 is lower. With and without the quadratic component, it does look like regardless of outcome distribution the quadratic piece is worth its weight, resulting in better predictions across AIC, BIC, -2LL, and marginal R2! Looking at everything together, seems like the quadratic model with a gamma/exponential distribution is the most appropriate. Let’s take a look at the raw model output.

summary(mod2)

Call:
glm(formula = CortStress2 ~ group * Cort_Stress_c + group * Cort_Stress_c2, 
    family = Gamma(link = "log"), data = data)

Coefficients:
                            Estimate Std. Error t value Pr(>|t|)    
(Intercept)                 -1.36621    0.17141  -7.970 1.83e-09 ***
groupControl                -0.07245    0.21724  -0.333 0.740694    
Cort_Stress_c                3.81618    0.90150   4.233 0.000152 ***
Cort_Stress_c2              -3.85300    6.18953  -0.623 0.537534    
groupControl:Cort_Stress_c   0.31240    1.37328   0.227 0.821336    
groupControl:Cort_Stress_c2  1.27535    6.22497   0.205 0.838823    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for Gamma family taken to be 0.2950553)

    Null deviance: 20.584  on 41  degrees of freedom
Residual deviance: 10.243  on 36  degrees of freedom
AIC: -71.221

Number of Fisher Scoring iterations: 6

As previously mentioned, the raw model output may help us feel more confident that these relationships are meaningful and clearly backs up the association we could visually see between first protocol cortisol and second protocol cortisol. Importantly, the raw model output doesn’t necessarily test the scientific hypothesis, because it only represents the probability that each model coefficient is equal to zero! At this point, we can use the L matrix to estimate the average stress cortisol for people who where high in stress cortisol in the first protocol and people who were low in cortisol, comparing between treatment and control, with the testable hypothesis that gratitude will have lower rates of cortisol (against the null hypothesis of no difference)!

A challenge in setting up the L matrices is we may not always have an intuitive idea for how much is “low” or “high” cortisol. One empirical option if we didn’t have an idea for how much difference is typical difference is to look at the standard deviation, which in this case is 0.3 (SD is a common mathematical definition of “typical difference”)! We’ll use that approach in this example. So for the linear terms, it will be -0.3 for “low cortisol” and 0.3 for “high cortisol”. For the quadratic terms, -0.32 = 0.32 = 0.09.

L_Specify(mod=mod2,
          Est_Num=4,
          type="Mean")
#Backing up our work
L=cbind(c(1, 0, -0.3, 0.09, 0, 0),
        c(1, 1, -0.3, 0.09, -0.3, 0.09),
        c(1, 0, 0.3, 0.09, 0, 0),
        c(1, 1, 0.3, 0.09, 0.3, 0.09))

Est_Names=c('1. Low Cort, Grat', '2. Low Cort, Ctrl', '3. High Cort, Grat', '4. High Cort, Ctrl')

Final Table

A quick check of how individual observations are influencing results before the final interpretation.

h=df_L(mod=mod2,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Biggest Increases                                                       
1 (+)                            23                22                 31
2 (+)                            30                37                 23
3 (+)                            25                29                 30
4 (+)                            11                 6                  3
5 (+)                            28                14                 28
Biggest Decreases                                                       
1 (-)                             5                26                  5
2 (-)                            15                10                 11
3 (-)                            42                 2                 15
4 (-)                            17                34                  7
5 (-)                            19                27                 41
                  4. High Cort, Ctrl
Biggest Increases                   
1 (+)                             10
2 (+)                             26
3 (+)                             14
4 (+)                             12
5 (+)                             40
Biggest Decreases                   
1 (-)                             22
2 (-)                              4
3 (-)                              2
4 (-)                             34
5 (-)                             29

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.145
                          

This does raise some concern that there might be somebody in the gratitude group with high cortisol at the first protocol who is impacting this average a great deal. You generally don’t want to remove people from the analysis unless you have additional evidence that a mistake in data entry of inclusion criteria was made, because how could you discern a true outlier from a bad model? But we will need to be cautious in drawing conclusions here because of this!

Let’s start with the Est_Mod() statement, just like before run twice for the two comparisons we wanted to make!

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            plot=c(1,2,3,4),
            ylab="Stress Cortisol",
            main="Stress Cortisol by Experimental Condition and First Protocol Cortisol")
                            
 Input L Matrix of Estimates
                            1. Low Cort, Grat 2. Low Cort, Ctrl
(Intercept)                              1.00              1.00
groupControl                             0.00              1.00
Cort_Stress_c                           -0.30             -0.30
Cort_Stress_c2                           0.09              0.09
groupControl:Cort_Stress_c               0.00             -0.30
groupControl:Cort_Stress_c2              0.00              0.09
                            3. High Cort, Grat 4. High Cort, Ctrl
(Intercept)                               1.00               1.00
groupControl                              0.00               1.00
Cort_Stress_c                             0.30               0.30
Cort_Stress_c2                            0.09               0.09
groupControl:Cort_Stress_c                0.00               0.30
groupControl:Cort_Stress_c2               0.00               0.09
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.06              0.05               0.57
95 % CI Lower Limit              0.02              0.03               0.19
95 % CI Upper Limit              0.16              0.11               1.69
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.27

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            diff=c(1,2),
            Print_L=F)
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.06              0.05               0.57
95 % CI Lower Limit              0.02              0.03               0.19
95 % CI Upper Limit              0.16              0.11               1.69
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.27
                                                                                  
 Ratio of 1. Low Cort, Grat and 2. Low Cort, Ctrl = 1.05, t(36) = 0.08, p =  0.934
hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            diff=c(3,4),
            Print_L=F)
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.06              0.05               0.57
95 % CI Lower Limit              0.02              0.03               0.19
95 % CI Upper Limit              0.16              0.11               1.69
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.27
                                                                                    
 Ratio of 3. High Cort, Grat and 4. High Cort, Ctrl = 0.87, t(36) = 0.22, p =  0.831

As we can see from the chart, there’s a strong relationship such that people who did not release a lot of cortisol in the first protocol also did not release a lot of cortisol in the second protocol. That said, differences between gratitude and control groups are small and imprecise. This does not support the scientific hypothesis. However, we did see that one of the estimates was greatly influenced by one individual, which is concerning. We’ll exclude that individual and run the analysis again to see if our conclusions would change. IMPORTANTLY, if the results do change (i.e., become significant), that isn’t very convincing evidence of the scientific hypothesis unless you had a better justification to remove this individual! All it would do is give us hope that this question may demonstrate more convincing evidence if the sample size were larger! This approach is often called sensitivity analysis.

mod2_Sensitivity=glm(CortStress2~group*Cort_Stress_c+group*Cort_Stress_c2,
                     family="Gamma"(link="log"),data=data[-c(5),]) #Dropping observation 5

hat=Est_Mod(mod=mod2_Sensitivity,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            plot=c(1,2,3,4),
            ylab="Stress Cortisol",
            main="Stress Cortisol by Experimental Condition and First Protocol Cortisol")
                            
 Input L Matrix of Estimates
                            1. Low Cort, Grat 2. Low Cort, Ctrl
(Intercept)                              1.00              1.00
groupControl                             0.00              1.00
Cort_Stress_c                           -0.30             -0.30
Cort_Stress_c2                           0.09              0.09
groupControl:Cort_Stress_c               0.00             -0.30
groupControl:Cort_Stress_c2              0.00              0.09
                            3. High Cort, Grat 4. High Cort, Ctrl
(Intercept)                               1.00               1.00
groupControl                              0.00               1.00
Cort_Stress_c                             0.30               0.30
Cort_Stress_c2                            0.09               0.09
groupControl:Cort_Stress_c                0.00               0.30
groupControl:Cort_Stress_c2               0.00               0.09
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.03              0.05               0.13
95 % CI Lower Limit              0.01              0.03               0.02
95 % CI Upper Limit              0.11              0.11               1.07
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.28

hat=Est_Mod(mod=mod2_Sensitivity,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            diff=c(1,2),
            Print_L=F)
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.03              0.05               0.13
95 % CI Lower Limit              0.01              0.03               0.02
95 % CI Upper Limit              0.11              0.11               1.07
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.28
                                                                                  
 Ratio of 1. Low Cort, Grat and 2. Low Cort, Ctrl = 0.57, t(35) = 0.79, p =  0.437
hat=Est_Mod(mod=mod2_Sensitivity,
            L=L,
            Est_Names=Est_Names,
            link="Log",
            diff=c(3,4),
            Print_L=F)
                    1. Low Cort, Grat 2. Low Cort, Ctrl 3. High Cort, Grat
Point Estimate                   0.03              0.05               0.13
95 % CI Lower Limit              0.01              0.03               0.02
95 % CI Upper Limit              0.11              0.11               1.07
                    4. High Cort, Ctrl
Point Estimate                    0.65
95 % CI Lower Limit               0.33
95 % CI Upper Limit               1.28
                                                                                  
 Ratio of 3. High Cort, Grat and 4. High Cort, Ctrl = 0.2, t(35) = 1.47, p =  0.15

While the estimated average for participants with high cortisol in the gratitude condition did decrease considerably, none of the p values changed significance. While we cannot accept the null hypothesis of no difference between gratitude and control groups, we have minimal evidence of a difference with and without this influential individual! All in all, it appears the personal trait of how much cortisol a person releases was much more relevant than the experimental condition!

Beta binomial regression

  • Theory: While we understand cortisol to be a biological mechanism of experiencing stress, the subjective appraisal of an experience as stressful or manageable is likely different than the physiological response, and may be impacted differently than biological measures
  • Scientific hypothesis: Participants who practice gratitude will report lower scores on a questionnaire assessing stress relative to the control group, but differences will be largest for participants who reported high stress prior to the experimental manipulation
  • Testable hypothesis: Using the L matrix, scores on the perceived stress scale will be lower for participants in the gratitude group at the second protocol, particularly for participants who demonstrated high stress ratings during the first protocol, an odds ratio less than one
  • Null hypothesis: All participants will have similar ratings on the perceived stress scale, numerically an odds ratio of one
  • Threat to validity: Stressors are most salient when they are immediately experienced, so measuring stress by a questionnaire may not actually represent the underlying experience of stress, especially this questionnaire which asks participants to reflect on their past week

It isn’t uncommon that you will have measures that have a limited scale. An easy example is questionnaires, where scores might range from 1-7, which means that scores can only fall within that range. You also might see “risk” groups, sorting patients into “low risk”, “moderate risk”, or “high risk” categories. You could analyze these as discrete groups, such as by logistic regression, but that loses a lot of information. There’s an inherent ordering to these groups, so looking at them as discrete groups may provide result that depend on the threshold you select for making comparison. However, there may be a problem with viewing them as raw numbers assuming a normal distribution. For example, if you have scores from 1-7, but everybody bunches up around 6 and 7, a normal distribution may not represent the anticipated skew in the data very well!

One solution is to conceptualize these as like a percentage! Mathematically, this is sometimes called a “percent of maximum scaling transformation”, but the idea is simple. The lowest possible score become 0%, the highest possible score becomes 100%, and any number in between is scaled to how many possible categories there are! So, for example, for a scale from 1-7, transformed percentages would be as follows:

  • 1 = 0/6 = 0%
  • 2 = 1/6 = 17%
  • 3 = 2/6 = 33%
  • 4 = 3/6 = 40%
  • 5 = 4/6 = 67%
  • 6 = 5/6 = 83%
  • 7 = 6/6 = 100%

Conversely, if the scale went from 1-5, 1 would still be 0%, but now 5 would be 100%, and the steps in between would be different:

  • 1 = 0/4 = 0%
  • 2 = 1/4 = 25%
  • 3 = 2/4 = 50%
  • 4 = 3/4 = 75%
  • 5 = 4/4 = 100%

This applies too for “risk groups”, such as:

  • “Low risk” = 0/2 = 0%
  • “Moderate risk” = 1/2 = 50%
  • “High risk” = 2/2 = 100%

This approach helps because it allows you to preserve the continuum that underpins the measures, while also accounting for their limited range of values. The specific equation used to perform this transformation is:

\(\ x^*_{i}=\frac{(x_i-min(X))}{(max(X)-min(X))}\)

where \(\ x^*_{i}\) is the transformed percentage score, \(\ x_{i}\) is the raw score, \(\ min(X)\) is the minimum possible raw score, and \(\ max(X)\) is the maximum possible raw score. Importantly, we can use the same glm() function with family=“binomial”(link=“logit”) that we used before to analyze these data!

In the dataset, if we wanted to analyze the 14 item Perceived Stress Scale, we might model this as a beta binomial percentage. This asks participants about how stressed they feel on a daily basis, rated from 0 (low stress) to 4 (high stress). Because there are 14 items, 14 * 4 = 56, so the smallest possible score a participant could receive is 0 (0 on all questions, very low stress), and the highest possible score a participant could receive is 56 (4 on all questions, very high stress). In this case, since the minimum possible is 0, we just need to divide each raw score by the maximum, 56! It obviously would be a lot to write out all scores here, but this is an example of the beginning and end for demonstration:

  • 0 = 0/56 = 0%

  • 1 = 1/56 = 2%

  • 2 = 2/56 = 4%

  • 3 = 3/56 = 5%

    ⋮

  • 53 = 53/56 = 95%

  • 54 = 54/56 = 96%

  • 55 = 55/56 = 98%

  • 56 = 56/56 = 100%

First, we need to process the scores

#First protocol
data$Stress_pct_BL=data$PSS1/56-mean(data$PSS1/56)
#First protocol, quadratic change
data$Stress_pct_BL2=data$Stress_pct_BL^2
#Second protocol
data$Stress_pct_FU=data$PSS2/56

We have strong reason to think this represents a beta binomial distribution, but we can confirm this using Plot_Dist()! This also helps confirm that we didn’t make a typo in coding the percentage transformation, which would result in values less than 0 or greater than 1.

Plot_Dist(data$Stress_pct_FU)

Beta Binomial Distribution

Not perfect, but we’ve accounted for the limits on scaling and some of the skew we can see! We’re hoping to see a difference in average ratings of stress exclusive to the gratitude group that isn’t overtaken by baseline stress scores, so let’s check that visually.

plot(data$Stress_pct_FU~data$group*data$Stress_pct_BL,
     main="Reported Stress by Experimental Condition and Baseline Stress Score",
     xlab="Experimental Condition or Baseline Stress Score",
     ylab="Reported Stress")

So far there is some evidence for the hypothesis, the gratitude group is reporting distinctly lower stress, but there is a strong association between first protocol stress scores and second protocol stress scores! The final test of the hypothesis would be from the regression model, which will account for how both of these intersect. We can also consider a linear and a quadratic trend for the first protocol perceived stress scale.

mod1=glm(Stress_pct_FU~group*Stress_pct_BL,family="binomial"(link="logit"),data=data)
Warning in eval(family$initialize): non-integer #successes in a binomial glm!
mod2=glm(Stress_pct_FU~group*Stress_pct_BL+group*Stress_pct_BL2,
         family="binomial"(link="logit"),data=data)
Warning in eval(family$initialize): non-integer #successes in a binomial glm!
#Don't worry about the warnings, they're just telling you that
#the outcome isn't 0 and 1 as is assumed in a binomial distribution,
#but we already knew that!
inspect_mods(mod=list(mod1,mod2),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2        Interpretation
Parameters        4       6     Smaller is better
AIC           37.71   41.96     Smaller is better
BIC           44.66   52.39     Smaller is better
-2LL          29.71   29.96     Smaller is better
Marginal R2    0.15    0.17 Closer to 1 is better

So both models have some problems with residuals, which is unfortunate, but there’s not a lot we can do about that! The quadratic model doesn’t seem to be adding a lot of value, but it does appear to have a little more symmetry in the histogram of residuals, so let’s go with that. Also we know the confidence intervals can’t imply impossible values, like a score greater than 56 or less than 0, so at least we covered that base even if the mode isn’t making the best predictions! Let’s start with a check of the inferences about each individual coefficient.

summary(mod2)

Call:
glm(formula = Stress_pct_FU ~ group * Stress_pct_BL + group * 
    Stress_pct_BL2, family = binomial(link = "logit"), data = data)

Coefficients:
                            Estimate Std. Error z value Pr(>|z|)
(Intercept)                   0.8229     0.6574   1.252    0.211
groupControl                  0.1643     0.8893   0.185    0.853
Stress_pct_BL                 5.2281     6.0913   0.858    0.391
Stress_pct_BL2               13.8758    46.9150   0.296    0.767
groupControl:Stress_pct_BL   -0.5593     9.9875  -0.056    0.955
groupControl:Stress_pct_BL2 -17.1756    66.6516  -0.258    0.797

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 4.0324  on 41  degrees of freedom
Residual deviance: 2.2760  on 36  degrees of freedom
AIC: 41.96

Number of Fisher Scoring iterations: 5

At this point, we can use the L matrix to make comparisons. Obviously the gratitude and control groups will just be 0 and 1 depending, as we’ve done before. For comparing high and low stress, the standard deviation in stress scores was 0.1, so we could put in -0.1 for low stress and 0.1 for high stress. That also implies for the quadratic terms 0.01 because -0.12 = 0.12 = 0.01.

L_Specify(mod=mod2,
          Est_Num=4,
          type="Mean")
#Backup code
L=cbind(c(1, 0, -0.1, 0.01, 0, 0),
        c(1, 1, -0.1, 0.01, -0.1, 0.01),
        c(1, 0, 0.1, 0.01, 0, 0),
        c(1, 1, 0.1, 0.01, 0.1, 0.01))

Est_Names=c('1. Low Stress, Grat', '2. Low Stress, Ctrl', '3. High Stress, Grat', '4. High Stress, Ctrl')

Final Table

One last diagnostic check before we look at the final results, we’ll check for reliability of model results!

h=df_L(mod=mod2,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 19 %
[1] 31 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 69 %
[1] 81 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Low Stress, Grat 2. Low Stress, Ctrl 3. High Stress, Grat
Biggest Increases                                                             
1 (+)                              38                  12                   25
2 (+)                              23                   8                    5
3 (+)                               3                  22                   38
4 (+)                              42                  37                   42
5 (+)                              19                  18                    9
Biggest Decreases                                                             
1 (-)                              25                   4                   19
2 (-)                              32                  33                    3
3 (-)                              15                  29                   32
4 (-)                              11                  14                   11
5 (-)                              41                  10                   23
                  4. High Stress, Ctrl
Biggest Increases                     
1 (+)                               33
2 (+)                               10
3 (+)                               26
4 (+)                               24
5 (+)                               40
Biggest Decreases                     
1 (-)                               22
2 (-)                                4
3 (-)                                8
4 (-)                               12
5 (-)                               18

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                        
  Leave One Out R2 = 0.3
                        

Reliability looks appropriate, most estimates only changing by 10%-20% when each individual is removed, and leave one out R2 isn’t small. And finally returning now to the Est_Mod() function to compare the reported stress scores. First we’ll compare people who reported low stress; and then the people who reported high stress! Note that this time, like with the binomial example we used a logit link, so we’ll need to specify that in the code!

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="logit",
            plot=c(1,2,3,4),
            ylab="Reported Stress",
            main="Reported Stress by Experimental Condition and Baseline Stress Score")
                            
 Input L Matrix of Estimates
                            1. Low Stress, Grat 2. Low Stress, Ctrl
(Intercept)                                1.00                1.00
groupControl                               0.00                1.00
Stress_pct_BL                             -0.10               -0.10
Stress_pct_BL2                             0.01                0.01
groupControl:Stress_pct_BL                 0.00               -0.10
groupControl:Stress_pct_BL2                0.00                0.01
                            3. High Stress, Grat 4. High Stress, Ctrl
(Intercept)                                 1.00                 1.00
groupControl                                0.00                 1.00
Stress_pct_BL                               0.10                 0.10
Stress_pct_BL2                              0.01                 0.01
groupControl:Stress_pct_BL                  0.00                 0.10
groupControl:Stress_pct_BL2                 0.00                 0.01
                    1. Low Stress, Grat 2. Low Stress, Ctrl
Point Estimate                     0.61                0.62
95 % CI Lower Limit                0.33                0.15
95 % CI Upper Limit                0.83                0.94
                    3. High Stress, Grat 4. High Stress, Ctrl
Point Estimate                      0.82                 0.81
95 % CI Lower Limit                 0.35                 0.45
95 % CI Upper Limit                 0.97                 0.95

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="logit",
            diff=c(1,2),
            Print_L=F)
                    1. Low Stress, Grat 2. Low Stress, Ctrl
Point Estimate                     0.61                0.62
95 % CI Lower Limit                0.33                0.15
95 % CI Upper Limit                0.83                0.94
                    3. High Stress, Grat 4. High Stress, Ctrl
Point Estimate                      0.82                 0.81
95 % CI Lower Limit                 0.35                 0.45
95 % CI Upper Limit                 0.97                 0.95
                                                                                      
 Ratio of 1. Low Stress, Grat and 2. Low Stress, Ctrl = 0.95, t(36) = 0.04, p =  0.969
hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="logit",
            diff=c(3,4),
            Print_L=F)
                    1. Low Stress, Grat 2. Low Stress, Ctrl
Point Estimate                     0.61                0.62
95 % CI Lower Limit                0.33                0.15
95 % CI Upper Limit                0.83                0.94
                    3. High Stress, Grat 4. High Stress, Ctrl
Point Estimate                      0.82                 0.81
95 % CI Lower Limit                 0.35                 0.45
95 % CI Upper Limit                 0.97                 0.95
                                                                                        
 Ratio of 3. High Stress, Grat and 4. High Stress, Ctrl = 1.07, t(36) = 0.05, p =  0.962

Doesn’t look like we found much of anything! As you might expect, people who reported high stress in the first protocol also tended to report high stress in the second protocol. That being said, the confidence intervals are wide enough, doesn’t look like anybody is that different than anybody else–there was just a lot of variation in perceived stress! Importantly, as you can see the confidence intervals aren’t symmetrical. This is the benefit of using the logit link, if we didn’t we’d probably have estimates that exceed the possible scaling of this questionnaire! All in all, looks like baseline stress was more relevant than gratitude condition.

Key Takeaways

  • It’s pretty hard to assume real world data are actually normally distributed, which by definition allow for the possibility of infinitely negative and infinitely large numbers!
  • While it is reasonable to assume our estimates of associations and differences are normally distributed, it may result in biased estimates to assume the raw data are normally distributed
  • By using a logit or log link, the model can account for these differences analytically
  • This can help better represent the probabilistic processes that underpin the raw data and ensure p values and confidence intervals don’t act under an assumption that the data can assume values that are not actually possible
  • Conveniently, it all fits within the same analytic framework we’ve used before, it is just better math!
  • There are many more distributions and link functions that can be used, these are just some of the more common choices

Topic 9: Random Effects for Repeated Measures

Learning Goals

Today we’ll examine how to deal with repeated observations on the same individuals in the dataset! This is an apt application for this project, because we have so many heart rate observations at two stages of a protocol, essentially ten heart rate observations per person (five pre and five post)! We need to model the correlations between the repeated observations on the same individuals to get good estimates of probability, but otherwise repeated measures analysis is trying to provide results in the same format as all the other regression approaches we’ve used so far!

Packages used:

  • glmmTMBB
  • Ray’s functions
library(glmmTMB)
source("https://raw.githubusercontent.com/JoshuaRayTanzer/Functions/main/Functions.R")

Modeling Heart Rate at Each Stage of Protocol

  • Theory: Some research has suggested that the experience of going through a stressful experience can lead you to a calmer resting state after the stressor is removed
  • Scientific hypothesis: If experiencing a stressful event can culminate in an ultimately less stressed state, then heart rates at recovery should be lower than they were at baseline despite the anticipated increases during the stress protocol
  • Testable hypothesis: Using the L matrix, the difference in heart rate averages between baseline and recovery will imply lower heart rate at recovery, a negative value
  • Null hypothesis: We will assume there is no change in heart rate averages, numerically a value of zero
  • Threat to validity: The experimenters were all known to the participants, so they may not actually be the right people to facilitate a task intended to induce stress

First we need to read the data in as usual

data=read.table("S:/Ray_R_Tools/Practical_Statistics/Data.txt",sep="\t",header=T)

Because there are multiple stages of the protocol, we’ll need to do some data processing to make a chart! First, we might like to have the average heart rate levels at each stage of the protocol.

HR=c(mean(data$HRBASE1),
     mean(data$HRPREP1),
     mean(data$HRTALK1),
     mean(data$HRMATH1),
     mean(data$HRRECOV1))

Next, it might be nice to see all the participants as individual lines on one chart. To do that, we can use a for loop! A for loop just tells R to run the same bit of code over and over again for a specified number of iterations. So, if we first start a plot using the plot() function, we can tell it to add lines to the plot. And we can add as many lines as there are individuals in the data, to get some sense of the trends over time as well as the variation in individual trajectories over time. Lastly, we can draw back on the average, but with a thicker line to make it stand out

plot(y=HR,x=0:4,type="l",
     main="Changes in Heart Rate over Protocol",
     xlab="Stage of Protocol",
     ylab="Heart Rate",
     ylim=c(50,120))
for(i in 1:nrow(data)){
  lines(y=c(data$HRBASE1[i],
            data$HRPREP1[i],
            data$HRTALK1[i],
            data$HRMATH1[i],
            data$HRRECOV1[i]),
        x=0:4,
        col="grey")
}
lines(y=HR,x=0:4,lwd=2)

Visually, it does appear to show the pattern of increases and decreases we anticipate, but let’s do some modeling to determine if these are meaningful changes! To do the modeling, we’ll need to convert what is currently in “wide” format into “long” format! Currently, each observation is a separate variable, hence the term “wide”. But to analyze it as a regression analysis, we’ll need to make each observation in the same column, one very “long” column!

y=c(data$HRBASE1,
    data$HRPREP1,
    data$HRTALK1,
    data$HRMATH1,
    data$HRRECOV1)
long=data.frame(y)

Next, we’ll need indicators of the stages of the protocol.

#note that the rep statement means repeat this value,
#the number repeats specified as nrow(data),
#or the number or records in the dataset.
long$protocol=c(rep(0,nrow(data)),
                rep(1,nrow(data)),
                rep(2,nrow(data)),
                rep(3,nrow(data)),
                rep(4,nrow(data)))

#We can do this as a factor...
long$protocol=as.factor(long$protocol)
long=within(long, protocol<-relevel(long$protocol,ref="0"))

#...or leave it as a continuous number!
long$protocol_cont=c(rep(0,nrow(data)),
                     rep(1,nrow(data)),
                     rep(2,nrow(data)),
                     rep(3,nrow(data)),
                     rep(4,nrow(data)))
long$protocol_cont2=long$protocol_cont^2

Because everybody is in the dataset five times, we’ll need an indicator of personal IDs as well!

#Using the rep statement again, so repeat the numbers from one to
#however many records are in the dataset, repeat that five times
long$ID=rep(1:nrow(data),5)
long$ID=as.factor(long$ID)

We are good to go, now to get into some models! One key question is how should we understand the relationships over time. We could look at each stage of the protocol separately as separate individual averages. A concern about that is it would mean a coefficient for each timepoint–that’s a lot of coefficients! Additionally, we’d need to model the associations between all those timepoints, again, that’s a lot! If we want to do that, we could consider an unstructured covariance matrix (estimate a coefficient for each covariance and variance), autoregressive (estimate a correlation over time that decreases as timepoints are more distant), or compound symmetry (estimate a single correlation between all timepoints). Autoregressive and compound symmetry help because that reduces the model complexity over the unstructured matrix, but it does mean simplifying the longitudinal structure to some extent.

#Unstructured
mod1=glmmTMB(y~protocol+us(0+protocol|ID),data=long,family=gaussian)
Warning in fitTMB(TMBStruc): Model convergence problem; non-positive-definite
Hessian matrix. See vignette('troubleshooting')
#Model convergence problem, computer can't find an answer,
#we may not be able to use this model!
#This happens sometimes, especially since we used an
#unstructured covariance matrix, which is pretty complex!

#Autoregressive
mod2=glmmTMB(y~protocol+ar1(0+protocol|ID),data=long,family=gaussian)

#Compound symmetry
mod3=glmmTMB(y~protocol+cs(0+protocol|ID),data=long,family=gaussian)

We can also look at time as a continuum. This means less parameters, so that simplifies things! But it also means assuming we can form a single line to connect all the dots without bias in the residuals. Additionally, when modeling the correlations between timepoints, now we will model the relationships between the individual intercepts, linear changes, and quadratic changes. This can be difficult for the model to find a solution. In that event, you can use diag() for the covariance matrix. This means not estimating the correlation between intercept and change parameters. That’s not ideal, but it also may not be clear whether or not you should expect these to be associated!

#Linear
mod4=glmmTMB(y~protocol_cont+us(1+protocol_cont|ID),data=long,family=gaussian)
#Quadratic
mod5=glmmTMB(y~protocol_cont+protocol_cont2+us(1+protocol_cont+protocol_cont2|ID),data=long,family=gaussian)
Warning in fitTMB(TMBStruc): Model convergence problem; non-positive-definite
Hessian matrix. See vignette('troubleshooting')
#Getting another model convergence problem, fortunately we have more options,
#we can simplify this model while keeping a similar conceptual design
#(diag estimates one variance per random effect,
#assumes uncorrelated random effects.  Not a preferred assumption,
#but sometimes you can't get the computer to work otherwise!)
mod5=glmmTMB(y~protocol_cont+protocol_cont2+diag(1+protocol_cont+protocol_cont2|ID),data=long,family=gaussian)

Now that we have all out models loaded, we can look at the residuals!

inspect_mods(mod=list(mod1,mod2,mod3,mod4,mod5),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2 Model 3 Model 4 Model 5        Interpretation
Parameters        5       5       5       2       3     Smaller is better
AIC            <NA> 1494.33 1488.49 1617.11 1504.48     Smaller is better
BIC            <NA> 1521.11 1528.65 1637.19 1527.91     Smaller is better
-2LL           <NA> 1478.33 1464.49 1605.11 1490.48     Smaller is better
Marginal R2       1    0.85       1    0.67    0.83 Closer to 1 is better

Clearly we can’t use model 1, computer can’t find a solution, it was just too complex! Most of these residuals look pretty good! The linear change over time model (mod4) clearly shows bias in the residuals, but otherwise they look fairly normal! The compound symmetry model (mod3) had clearly the best fit across the model fit metrics, so we’ll go with that model.

summary(mod3)
 Family: gaussian  ( identity )
Formula:          y ~ protocol + cs(0 + protocol | ID)
Data: long

     AIC      BIC   logLik deviance df.resid 
  1488.5   1528.7   -732.2   1464.5      198 

Random effects:

Conditional model:
 Groups   Name      Variance  Std.Dev. Corr     
 ID       protocol0 1.387e+02 11.77598 0.77 (cs)
          protocol1 1.543e+02 12.42243          
          protocol2 2.267e+02 15.05677          
          protocol3 1.618e+02 12.72002          
          protocol4 1.125e+02 10.60713          
 Residual           2.279e-06  0.00151          
Number of obs: 210, groups:  ID, 42

Dispersion estimate for gaussian family (sigma^2): 2.28e-06 

Conditional model:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)   75.312      1.817   41.45  < 2e-16 ***
protocol1      7.290      1.261    5.78 7.43e-09 ***
protocol2     13.902      1.474    9.43  < 2e-16 ***
protocol3      5.689      1.280    4.44 8.86e-06 ***
protocol4     -3.310      1.175   -2.82  0.00487 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Visually, it would appear things are acting as we think they should, with an increase during the stress tasks and then the hypothesized decrease at recovery. But it’d be nice to see this visually, so we can use the L matrix to get estimated averages! Additionally, we can use the L matrix to verify that our conclusions aren’t reliant on the chance heart rate values of a handful of individuals!

First we start with setting up the L matrix for each stage of the protocol. Since these are all binary dummy variables, all we need to do is set up each estimate!

L_Specify(mod=mod3,
          Est_Num=5,
          type="Mean")
#Always make sure to back up
L=cbind(c(1, 0, 0, 0, 0),
        c(1, 1, 0, 0, 0),
        c(1, 0, 1, 0, 0),
        c(1, 0, 0, 1, 0),
        c(1, 0, 0, 0, 1))

Est_Names=c('Baseline', 'Preparation', 'Speech', 'Math', 'Recovery')

Finished Table

Next, we can check the reliability of the model estimates!

h=df_L(mod=mod3,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 20 %
[1] 30 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 70 %
[1] 80 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Baseline Preparation Speech Math Recovery
Biggest Increases                                          
1 (+)                   36          82     99  164      169
2 (+)                   28          52    118  155      172
3 (+)                   22          77     89  142      192
4 (+)                    4          61     97  128      205
5 (+)                   18          55    124  163      189
Biggest Decreases                                          
1 (-)                   16          54     85  141      186
2 (-)                   41          46    112  154      178
3 (-)                   40          51     88  145      173
4 (-)                   38          66    123  139      202
5 (-)                    5          79    121  150      182

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.748
                          

This supports that the estimates are extremely reliable, no one individual influencing any estimate by more than half a percentage and a very large leave one out R2!

Finally, we just need to run the Est_Mod() statement! This time, since this is a longitudinal comparison, we can specify plot_type as “line”, which will create a line chart rather than a bar chart!

hat=Est_Mod(mod=mod3,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4,5),
            plot_type="line",
            diff=c(1,5),
            ylab="Heart Rate",
            main="Heart Rate over Stages of Protocol")
                            
 Input L Matrix of Estimates
            Baseline Preparation Speech Math Recovery
(Intercept)        1           1      1    1        1
protocol1          0           1      0    0        0
protocol2          0           0      1    0        0
protocol3          0           0      0    1        0
protocol4          0           0      0    0        1
                    Baseline Preparation Speech  Math Recovery
Point Estimate         75.31       82.60  89.21 81.00    72.00
Standard Error          1.82        1.92   2.32  1.96     1.64
95 % CI Lower Limit    71.73       78.82  84.63 77.13    68.78
95 % CI Upper Limit    78.89       86.38  93.80 84.87    75.23
                                                                           
 Difference between Baseline and Recovery = 3.31, t(204) = 2.82, p =  0.005

Clearly there are some big increases during the stress task as we anticipated, and we could tell those were significant from the summary statement. Specifically testing the difference from baseline to recovery, there is evidence to reject the null hypotheesis of no difference, evidence in support of the sceintific hypothesis that heart rates would be lower at recovery following the sress protocol.

At this point, we would probably stop and move on to whatever next questions are. However, for the sake of demonstration it is worth demonstrating how to specify the L matrix using the quadratic model! Since the scaling went from 0 to 4, we’ll have linear inputs that go from 0 to 4, and quadratic inputs that are 02 = 0, 12 = 1, 22 = 4, 32 = 9, and 42 = 16. We can do this using the L_Specify() function as before!

L_Specify(mod5,
          Est_Num=5,
          type="Mean")
#Saving our work
L=cbind(c(1, 0, 0),
        c(1, 1, 1),
        c(1, 2, 4),
        c(1, 3, 9),
        c(1, 4, 16))

Est_Names=c('Baseline', 'Preparation', 'Speech', 'Math', 'Recovery')

Finished Table

Next, we can check the reliability of the estimates.

h=df_L(mod=mod5,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 20 %
[1] 30 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 70 %
[1] 80 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  Baseline Preparation Speech Math Recovery
Biggest Increases                                          
1 (+)                   36          99     99   99      205
2 (+)                   28         118    118  118      169
3 (+)                    4          97     97  164      172
4 (+)                   22         124    164   97      189
5 (+)                   12          89    124  124      196
Biggest Decreases                                          
1 (-)                   16          85     85  141      186
2 (-)                   41          54    141   85      178
3 (-)                   40         123    123  145      173
4 (-)                   38          46    112  123      202
5 (-)                   34          51    121  154      204

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.735
                          

This model is also extremely reliable, variation in estimates now only about a quarter of a percentage for any one individual! Finally we can use Est_Mod() like before.

hat=Est_Mod(mod=mod5,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4,5),
            plot_type="line",
            diff=c(1,5),
            ylab="Heart Rate",
            main="Heart Rate over Stages of Protocol")
                            
 Input L Matrix of Estimates
               Baseline Preparation Speech Math Recovery
(Intercept)           1           1      1    1        1
protocol_cont         0           1      2    3        4
protocol_cont2        0           1      4    9       16
                    Baseline Preparation Speech  Math Recovery
Point Estimate         74.90       84.23  86.80 82.59    71.61
Standard Error          1.93        1.79   1.82  1.79     1.93
95 % CI Lower Limit    71.10       80.70  83.20 79.05    67.81
95 % CI Upper Limit    78.70       87.77  90.39 86.13    75.41
                                                                           
 Difference between Baseline and Recovery = 3.29, t(206) = 2.64, p =  0.009

Seems to be telling more or less the same story, a bit more articulated because we forced it into a curve, so we probably didn’t need to do both for scientific purposes! But it is valuable to demonstrate how to set up the L matrix properly, because the quadratic model is much simpler even if it doesn’t fit the data quite as well!

Generalized Model Example

  • Theory: Young people are known for feeling a sense of invincibility, so they may developmentally have a different cortisol release rate during a stressful circumstance
  • Scientific hypothesis: Younger participants will release less cortisol on average, especially following the stress task
  • Testable hypothesis: Using the L matrix, younger participants will have on average less cortisol released following the stress task compared to older participants, a rate ratio less than one
  • Null hypothesis: We will assume there no differences in cortisol release, numerically a ratio of one
  • Threat to validity: This sample is primarily of 18-22 year olds, which may not fully represent the age range in which the perception of invincibility reduces
  • Threat to validity: The sense of invincibility may be more relevant to more dangerous situations than giving a speech

First, it’s always nice to start with a plot, using the for loop like before!

delta=c(mean(data$CortBase1),
        mean(data$CortStress1))

plot(y=delta,x=0:1,type="l",
     main="Changes in Cortisol Pre and Post Stress",
     xlab="Pre or Post",
     ylab="Cortisol",
     log="y",
     ylim=c(0.01,2))
for(i in 1:nrow(data)){
  lines(y=c(data$CortBase1[i],
            data$CortStress1[i]),
        x=0:1,
        col="grey")
}
lines(y=delta,x=0:1,lwd=2)

Visually, it does not appear there was much change in cortisol, but there clearly are a few people who increased cortisol quite a bit! We’ll have to see how this intersects with age. Like before, we need to start with some data processing.

#Changing outcome from "wide" to "long" format
y=c(data$CortBase1,data$CortStress1)
long=data.frame(y)

#Creating a variable identifying pre from post stress protocol
long$prepost=c(rep(0,nrow(data)),
               rep(1,nrow(data)))
long$prepost=as.factor(long$prepost)

#Keeping track of ages
long$age_c=rep(data$AGE-mean(data$AGE),2)
long$age_c2=long$age^2

#Creating IDs
long$ID=rep(1:nrow(data),2)
long$ID=as.factor(long$ID)

We can also make a chart comparing cortisol by ages

plot(y=long$y,x=long$age_c,
     main="Cortisol Levels by Age",
     xlab="Age",
     ylab="Cortisol",
     log="y")

We can also check out cortisol itself using Plot_Dist()

Plot_Dist(long$y)

Cortisol

Assuming an exponential/gamma distribution does not seem inappropriate, however there were some people with really high cortisol! We’ll hope this can be explained by age in the model!

We’ll want to consider a linear relationship as well as quadratic, as usual! In this case, it doesn’t make much of a difference what structure we use for the covariance matrix because there’s only two timepoints

mod1=glmmTMB(y~prepost*age_c+us(0+prepost|ID),
             data=long,family=Gamma(link = "log"))
Warning in fitTMB(TMBStruc): Model convergence problem; singular convergence
(7). See vignette('troubleshooting')
mod2=glmmTMB(y~prepost*age_c+prepost*age_c2+us(0+prepost|ID),
             data=long,family=Gamma(link = "log"))
Warning in (function (start, objective, gradient = NULL, hessian = NULL, :
NA/NaN function evaluation

Warning in (function (start, objective, gradient = NULL, hessian = NULL, :
Model convergence problem; singular convergence (7). See
vignette('troubleshooting')

Clearly the computer isn’t having an easy time finding a numeric solution–that happens sometimes, especially when you have repeated measures and non-normal measures! We’ll just need to review the model fit diagnostics carefully!

inspect_mods(mod=list(mod1,mod2),
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
            Model 1 Model 2        Interpretation
Parameters        4       6     Smaller is better
AIC         -113.22  -119.6     Smaller is better
BIC          -93.77   -95.3     Smaller is better
-2LL        -129.22  -139.6     Smaller is better
Marginal R2    0.74    0.79 Closer to 1 is better

In both cases, we have some problems with residuals, some very extreme over and under estimates! However, the quadratic model does appear to have better fit for everything, even BIC which penalizes more complex models the most. For that reason, we’ll go with the quadratic model!

summary(mod2)
 Family: Gamma  ( log )
Formula:          y ~ prepost * age_c + prepost * age_c2 + us(0 + prepost | ID)
Data: long

     AIC      BIC   logLik deviance df.resid 
  -119.6    -95.3     69.8   -139.6       74 

Random effects:

Conditional model:
 Groups Name     Variance Std.Dev. Corr 
 ID     prepost0 0.3810   0.6172        
        prepost1 0.5052   0.7108   1.00 
Number of obs: 84, groups:  ID, 42

Dispersion estimate for Gamma family (sigma^2): 0.144 

Conditional model:
                 Estimate Std. Error z value Pr(>|z|)    
(Intercept)     -1.748131   0.122838 -14.231  < 2e-16 ***
prepost1         0.155170   0.094874   1.636 0.101935    
age_c           -0.054053   0.069093  -0.782 0.434024    
age_c2           0.001727   0.006711   0.257 0.796895    
prepost1:age_c   0.170236   0.052906   3.218 0.001292 ** 
prepost1:age_c2 -0.017530   0.005096  -3.440 0.000582 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Clearly there’s something dynamic going on related to age, especially so far as it relates to cortisol release following the stress protocol! Let’s make some estimates. Since we centered age around 20, we’ll consider younger age as a value in the L matrix as -2 (about 18); and older age as a value of 2 (about 22), which should more or less span the majority of ages in the dataset. The quadratic inputs will be 4 for both because -22 = 22 = 4. For pre and post, it will just be 0 for pre and 1 for post. Now we just need to set it up with L_Specify()!

L_Specify(mod2,
          Est_Num=4,
          type="Mean")
#Saving work
L=cbind(c(1, 0, -2, 4, 0, 0),
        c(1, 1, -2, 4, -2, 4),
        c(1, 0, 2, 4, 0, 0),
        c(1, 1, 2, 4, 2, 4))

Est_Names=c('1. Younger, Pre', '2. Younger, Post', '3. Older, Pre', '4. Older, Post')

Finished Table

As one last check of model reliability, we can check how the individual date points impacted the model estimates.

h=df_L(mod=mod2,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 20 %
[1] 30 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 70 %
[1] 80 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
Biggest Increases                                                              
1 (+)                          25               57             2             56
2 (+)                          23               44            33             60
3 (+)                          33               43            34             80
4 (+)                          12               69            24             79
5 (+)                          42               65            26             45
Biggest Decreases                                                              
1 (-)                           2               47            14             44
2 (-)                          26               54            44              2
3 (-)                          15               67            38             82
4 (-)                           6               64            18             61
5 (-)                          27               82            37             76

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.011
                          

It is concerning that there is one individual dragging down the estimate for the older post estimate, however it is only by 15% so it isn’t a huge change. We can finally get a more detailed comparison of how age intersected with cortisol release! We’ll do younger age and then older age, so we can compare directly with the line plots

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="log",
            plot=c(1,2),
            plot_type="line",
            diff=c(1,2),
            ylab="Cortisol",
            main="Cortisol Levels Pre and Post Stress, Younger Participants")
                            
 Input L Matrix of Estimates
                1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
(Intercept)                   1                1             1              1
prepost1                      0                1             0              1
age_c                        -2               -2             2              2
age_c2                        4                4             4              4
prepost1:age_c                0               -2             0              2
prepost1:age_c2               0                4             0              4
                    1. Younger, Pre 2. Younger, Post 3. Older, Pre
Point Estimate                 0.20             0.15          0.16
95 % CI Lower Limit            0.14             0.10          0.11
95 % CI Upper Limit            0.27             0.22          0.23
                    4. Older, Post
Point Estimate                0.24
95 % CI Lower Limit           0.16
95 % CI Upper Limit           0.37
                                                                               
 Ratio of 1. Younger, Pre and 2. Younger, Post = 1.29, t(77) = 2.03, p =  0.046

hat=Est_Mod(mod=mod2,
            L=L,
            Est_Names=Est_Names,
            link="log",
            plot=c(3,4),
            plot_type="line",
            diff=c(3,4),
            ylab="Cortisol",
            main="Cortisol Levels Pre and Post Stress, Older Participants")
                            
 Input L Matrix of Estimates
                1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
(Intercept)                   1                1             1              1
prepost1                      0                1             0              1
age_c                        -2               -2             2              2
age_c2                        4                4             4              4
prepost1:age_c                0               -2             0              2
prepost1:age_c2               0                4             0              4
                    1. Younger, Pre 2. Younger, Post 3. Older, Pre
Point Estimate                 0.20             0.15          0.16
95 % CI Lower Limit            0.14             0.10          0.11
95 % CI Upper Limit            0.27             0.22          0.23
                    4. Older, Post
Point Estimate                0.24
95 % CI Lower Limit           0.16
95 % CI Upper Limit           0.37
                                                                           
 Ratio of 3. Older, Pre and 4. Older, Post = 0.65, t(77) = 2.85, p =  0.006

Clearly age was quite relevant here! At first pass, it appears to be consistent with the testable hypothesis, older participants showed significant increases in cortisol! However, younger participants actually showed decreases in cortisol on average, decreases large enough to reject the null hypothesis of no change! We did not expect this at first, but it is consistent with research suggesting younger people may appraise stress in a more positive light, as something fun!

Before running too far with these results, though, a major criticism is that the residuals are are concerning, as well as one individual who was drawing the estimates down for one estimate. To address this, we can perform a basic sensitivity analysis. As mentioned before, you should generally be cautious in labeling any individual an outlier unless you have specific evidence an error was made in data entry or the individual should not have been included in the sample. The concern is that we do not know if an individual is truly an outlier, or if the model was just bad. However, it was clear that there was one person, record ID 2, who had much higher cortisol than anybody else, and the model had very large residuals for this individual. They may or may not be an outlier, we don’t know, but we do know this model isn’t representing them well. The concern is the current model supports our hypothesis, but what if our conclusions hinge on this one individual the model is not representing well? This sensitivity analysis will help investigate that concern!

mod2_Sensitivity=glmmTMB(y~prepost*age_c+prepost*age_c2+us(0+prepost|ID),
                         data=long[long$ID!=2,],family=Gamma(link = "log"))

inspect_mods(mod=mod2_Sensitivity,
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
              Model        Interpretation
Parameters        6     Smaller is better
AIC         -140.76     Smaller is better
BIC         -116.69     Smaller is better
-2LL        -160.76     Smaller is better
Marginal R2    0.88 Closer to 1 is better
h=df_L(mod=mod2_Sensitivity,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 20 %
[1] 30 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 70 %
[1] 80 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
Biggest Increases                                                              
1 (+)                          24               55            32             58
2 (+)                          29               42            33             54
3 (+)                           4               63            29             78
4 (+)                          11               67            10             43
5 (+)                          39               46            39             77
Biggest Decreases                                                              
1 (-)                          14               45            13             51
2 (-)                          26               52            37             74
3 (-)                          25               65            17             59
4 (-)                           5               62             2             80
5 (-)                          34               80            36             55

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                      
  Leave One Out R2 = 0
                      

Residuals look much better, and no one individual is impacting the estimated averages much beyond two or three percent.

hat=Est_Mod(mod=mod2_Sensitivity,
            L=L,
            Est_Names=Est_Names,
            link="log",
            plot=c(1,2),
            plot_type="line",
            diff=c(1,2),
            ylab="Cortisol",
            main="Cortisol Levels Pre and Post Stress, Younger Participants")
                            
 Input L Matrix of Estimates
                1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
(Intercept)                   1                1             1              1
prepost1                      0                1             0              1
age_c                        -2               -2             2              2
age_c2                        4                4             4              4
prepost1:age_c                0               -2             0              2
prepost1:age_c2               0                4             0              4
                    1. Younger, Pre 2. Younger, Post 3. Older, Pre
Point Estimate                 0.19             0.16          0.15
95 % CI Lower Limit            0.14             0.11          0.10
95 % CI Upper Limit            0.27             0.22          0.22
                    4. Older, Post
Point Estimate                0.19
95 % CI Lower Limit           0.13
95 % CI Upper Limit           0.29
                                                                               
 Ratio of 1. Younger, Pre and 2. Younger, Post = 1.23, t(75) = 2.03, p =  0.046

hat=Est_Mod(mod=mod2_Sensitivity,
            L=L,
            Est_Names=Est_Names,
            link="log",
            plot=c(3,4),
            plot_type="line",
            diff=c(3,4),
            ylab="Cortisol",
            main="Cortisol Levels Pre and Post Stress, Older Participants")
                            
 Input L Matrix of Estimates
                1. Younger, Pre 2. Younger, Post 3. Older, Pre 4. Older, Post
(Intercept)                   1                1             1              1
prepost1                      0                1             0              1
age_c                        -2               -2             2              2
age_c2                        4                4             4              4
prepost1:age_c                0               -2             0              2
prepost1:age_c2               0                4             0              4
                    1. Younger, Pre 2. Younger, Post 3. Older, Pre
Point Estimate                 0.19             0.16          0.15
95 % CI Lower Limit            0.14             0.11          0.10
95 % CI Upper Limit            0.27             0.22          0.22
                    4. Older, Post
Point Estimate                0.19
95 % CI Lower Limit           0.13
95 % CI Upper Limit           0.29
                                                                           
 Ratio of 3. Older, Pre and 4. Older, Post = 0.76, t(75) = 2.18, p =  0.032

Returning to the estimated changes over time, clearly we would draw the same conclusions even if we remove the individual with ID 2. While you can demonstrate problems in a model, you’ll never know how well the model has met the assumptions. However, this sensitivity analysis has supported that our conclusions would be the same even if we removed one individual we know was not being very well represented by the model.

General Structure to the Data

Random effects analysis is useful for longitudinal data because longitudinal data have a lot of structure (i.e., the same people observed repeatedly over time). Importantly, an advantage of random effects is because they can analytically address other forms of structure in the data beyond specifically longitudinal designs! For example, if you were involved with a multi-site trial, you would anticipate each hospital to have different characteristics in terms of patient load, disease severity, and resources available, which could result in different patient health outcomes. You may not be interested in comparing each and every clinic, but it also would be inappropriate to not account for the differences by clinic within the model. Especially if there were many participating sites, it may not be feasible computationally to include clinical site as a categorical variable in the model, and you may not be interested in comparing each clinical site to any particular reference site. Random effects can be used to estimate an unique average for each participating site, addressing the known structure to the data without resulting in an uninterpretable model! An observational application, if you have hospital data, you might have the same people coming into the clinic more than once for different problems. The reasons a patient would come to the hospital may be different, so you may not want to exclude these patients from the analysis. Like before, it would be inappropriate to assume each hospitalization is completely independent of another hospitalization for the same patient, because some people just recover quickly and other people just recover slowly! But, especially with large datasets, it would be unhelpful to estimate a separate coefficient for each individual patient in comparison to one reference patient. Random effects can allow the model to estimate an average for each individual without adding it to the final model solution used for testing the scientific hypothesis. This improves the analytics because it accounts for the known structure to the data without complicating to the final model solution used for making inferences.

In the case of our gratitude trial, there were two iterations of the stress protocol, which each included at each iteration preparing and giving a speech to the experimenters. Because it would be essentially a different task for participants to prepare and give the same speech at the second stage of the stress protocol, we prepared two speech prompts! Participants gave a speech where they had to defend themselves after having been accused of cheating; and they also had to prepare a speech about interviewing for a job. Importantly, we randomly assigned which speech they gave at the first and second stage of the protocol. While we thought the two prompts were similarly stressful, we did not want to assume this! Additionally, we weren’t interested in comparing which prompt was more stressful, we were just worried it was inappropriate to assume they weren’t the same! To account for a possible difference, we can use random effects to account for this known structure to the data. Otherwise, the focus will be on comparing gratitude and control conditions, but this will address the threat to validity that the two stress prompts were not equally stressfull.

  • Theory: Practicing gratitude will help individuals to better appraise difficult life circumstances in a less stressful way, which will help to prevent spikes in heart rate during a stress task
  • Scientific hypothesis: Participants in the gratitude condition will tend toward lower heart rate averages during stress
  • Testable hypothesis: Using the L matrix to estimate the average heart rates during the speech task of the stress protocol, the difference between gratitude and control will imply lower heart rate for the gratitude condition during the second stage of the protocol, a negative value
  • Null hypothesis: We will assume there no differences in heart rate, numerically a difference of zero for all comparisons
  • Threat to validity: Because there were two speech prompts, a difference in prompt stressfulness may be more relevant than experimental condition (addressed by the random effect!)
  • Threat to validity: Because all participants will have encountered the stress protocol once before, regardless of which prompt is provided, anticipation or familiarity with the protocol may account for more changes than experimental condition

To make a chart, we will need to do some reformatting like before. We can start by getting the averages during the math task for gratitude and control groups at the first protocol and the second protocol.

HR_grat=c(mean(subset(data$HRTALK1,data$CONDITION==1)),
          mean(subset(data$HRTALK2,data$CONDITION==1)))
HR_ctrl=c(mean(subset(data$HRTALK1,data$CONDITION==2)),
          mean(subset(data$HRTALK2,data$CONDITION==2)))

Like before, we can use for loops to plot each individual change on the same chart with the averages! To do that, we’ll need to start with the plot() statement so that we can use the lines() statement to add each individual line Because we want to plot gratitude and control in different colors, we’ll need to do two for loops to cycle through both groups of data. Then at the end, we can add in two final lines() statements to put the averages on.

plot(y=HR_grat,x=1:2,type="l",
     main="Speech Heart Rate Between Experimental Groups",
     xlab="Stage of Protocol",
     ylab="Heart Rate",
     ylim=c(50,120))

#Gratitude data
for(i in 1:nrow(subset(data,data$CONDITION==1))){
  lines(y=c(subset(data$HRTALK1,data$CONDITION==1)[i],
            subset(data$HRTALK2,data$CONDITION==1)[i]),
        x=1:2,
        col="pink")
}

#Control data
for(i in 1:nrow(subset(data,data$CONDITION==2))){
  lines(y=c(subset(data$HRTALK1,data$CONDITION==2)[i],
            subset(data$HRTALK2,data$CONDITION==2)[i]),
        x=1:2,
        col="grey")
}

lines(y=HR_grat,x=1:2,lwd=2,col="red")
lines(y=HR_ctrl,x=1:2,lwd=2,col="black")

Visually speaking, doesn’t appear like there’s a lot going on between the two averages! However, you can see some of the individual trajectories going up and down, so doing an analysis that accounts for changes within individuals may clarify these differences!

First we’ll need to do some data processing!

data$group=ifelse(data$CONDITION==1,"Gratitude","Control")
data$group=as.factor(data$group)
data=within(data, group<-relevel(data$group,ref="Gratitude"))

y=c(data$HRTALK1,
    data$HRTALK2)
long=data.frame(y)

Next, we’ll need to create unique IDs and make some identifiers for experimental condition, math task received, and stage of the protocol (pre or post)!

#Pre or post stress protocol
long$prepost=c(rep(0,nrow(data)),
               rep(1,nrow(data)))
long$prepost=as.factor(long$prepost)

#Experimental condition
long$group=rep(data$group,2)

#Speech prompt
long$prompt=c(data$PROMPT1,
              data$PROMPT2)
long$prompt=as.factor(long$prompt)

#Creating IDs
long$ID=rep(1:nrow(data),2)
long$ID=as.factor(long$ID)

And now we are ready to fit the model! Note that we have two random effect statements this time, one where the identifier is ID, and the other where the identifier is the math prompt! We aren’t really interested in the math prompt, nor are we expecting to see meaningful differences, but it would be inappropriate to proclude the possibility of it mattering when it is this easy to account for!

mod=glmmTMB(y~prepost*group+us(0+prepost|ID)+us(1|prompt),
            data=long,family=gaussian)

inspect_mods(mod=mod,
             Plots=c("Histogram","QQ"))

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                                                     
 Number lines for interpretation of model fit metrics
                                                  
     For the -2LL, AIC, and BIC:                  
     Better                                  Worse
     <----------|----------|----------|---------->
     (Negative             0             (Positive
     numbers)                             numbers)
                                                  
     For Marginal R2:                             
     Worse                                  Better
     |----------|----------|----------|----------|
     0.00                0.50                 1.00
                                                  
              
 Model Results
             Model        Interpretation
Parameters       4     Smaller is better
AIC         681.62     Smaller is better
BIC          703.5     Smaller is better
-2LL        663.62     Smaller is better
Marginal R2      1 Closer to 1 is better

Visually, residuals are looking good, and the model coefficients appear reliable! Let’s take a look at the model results.

summary(mod)
 Family: gaussian  ( identity )
Formula:          y ~ prepost * group + us(0 + prepost | ID) + us(1 | prompt)
Data: long

     AIC      BIC   logLik deviance df.resid 
   681.6    703.5   -331.8    663.6       75 

Random effects:

Conditional model:
 Groups   Name        Variance  Std.Dev.  Corr 
 ID       prepost0    2.145e+02 14.645306      
          prepost1    2.256e+02 15.020754 0.73 
 prompt   (Intercept) 1.264e-06  0.001124      
 Residual             4.892e+00  2.211801      
Number of obs: 84, groups:  ID, 42; prompt, 2

Dispersion estimate for gaussian family (sigma^2): 4.89 

Conditional model:
                      Estimate Std. Error z value Pr(>|z|)    
(Intercept)            89.5397     3.2321  27.703   <2e-16 ***
prepost1               -2.0317     2.4862  -0.817    0.414    
groupControl           -0.6508     4.5709  -0.142    0.887    
prepost1:groupControl  -1.8095     3.5160  -0.515    0.607    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So far doesn’t look like a lot of evidence in support of the hypothesis, but this hasn’t really tested the comparison we were interested in. Let’s see if the L matrix gives an insight!

L_Specify(mod=mod,
          Est_Num=4,
          type="Mean")
#Copying and pasting the output backup code
L=cbind(c(1, 0, 0, 0),
        c(1, 0, 1, 0),
        c(1, 1, 0, 0),
        c(1, 1, 1, 1))

Est_Names=c('1. Grat, BL', '2. Ctrl, BL', '3. Grat, FU', '4. Ctrl, FU')

Finished Table

So we have four estimates for gratitude and control at the first protocol and the second protocol, and we are hypothesizing a difference between groups at the second protocol but not the first protocol. Let’s check the model reliability before getting into the final results.

h=df_L(mod=mod,
       L=L,
       Est_Names=Est_Names)
[1] Beginning influence analysis (this may take some time)
[1] 10 %
[1] 20 %
[1] 30 %
[1] 40 %
[1] 50 %
[1] 60 %
[1] 70 %
[1] 80 %
[1] 90 %
[1] 100 %
                                                                            
  The row IDs resulting in the largest increases and decreases in estimates:
                                                                            
                  1. Grat, BL 2. Ctrl, BL 3. Grat, FU 4. Ctrl, FU
Biggest Increases                                                
1 (+)                      15          34          61          82
2 (+)                      36          18          70          64
3 (+)                      30          26          43          48
4 (+)                      42           2          80          75
5 (+)                      32          20          63          81
Biggest Decreases                                                
1 (-)                      28          39          57          76
2 (-)                      19          37          72          60
3 (-)                       1          12          74          56
4 (-)                       7          33          51          54
5 (-)                      21          40          73          68

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot

Press enter to proceed to the next plot
                          
  Leave One Out R2 = 0.426
                          

Our estimates appear to be reliable, no one individual increasing or decreasing the estimates by a percentage or two, and leave one out R2 is large. Est_Mod() can now be used to test our hypothesis!

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=Est_Names,
            plot=c(1,2,3,4),
            ylab="Speech Heart Rate",
            main="Speech Heart Rate by Experimental Condition")
                            
 Input L Matrix of Estimates
                      1. Grat, BL 2. Ctrl, BL 3. Grat, FU 4. Ctrl, FU
(Intercept)                     1           1           1           1
prepost1                        0           0           1           1
groupControl                    0           1           0           1
prepost1:groupControl           0           0           0           1
                    1. Grat, BL 2. Ctrl, BL 3. Grat, FU 4. Ctrl, FU
Point Estimate            89.54       88.89       87.51       85.05
Standard Error             3.23        3.23        3.31        3.31
95 % CI Lower Limit       83.11       82.46       80.91       78.45
95 % CI Upper Limit       95.97       95.32       94.10       91.64

hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=Est_Names,
            diff=c(1,2),
            Print_L=F)
                    1. Grat, BL 2. Ctrl, BL 3. Grat, FU 4. Ctrl, FU
Point Estimate            89.54       88.89       87.51       85.05
Standard Error             3.23        3.23        3.31        3.31
95 % CI Lower Limit       83.11       82.46       80.91       78.45
95 % CI Upper Limit       95.97       95.32       94.10       91.64
                                                                                
 Difference between 1. Grat, BL and 2. Ctrl, BL = 0.65, t(79) = 0.14, p =  0.887
hat=Est_Mod(mod=mod,
            L=L,
            Est_Names=Est_Names,
            diff=c(3,4),
            Print_L=F)
                    1. Grat, BL 2. Ctrl, BL 3. Grat, FU 4. Ctrl, FU
Point Estimate            89.54       88.89       87.51       85.05
Standard Error             3.23        3.23        3.31        3.31
95 % CI Lower Limit       83.11       82.46       80.91       78.45
95 % CI Upper Limit       95.97       95.32       94.10       91.64
                                                                                
 Difference between 3. Grat, FU and 4. Ctrl, FU = 2.46, t(79) = 0.53, p =  0.601

Consistent with what we saw on the chart, we do not have evidence of meaningful differences between experimental groups. While this does not necessarily mean a difference did not exist between the two groups, we don’t have much evidence at this point that it did! It would appear the individual differences in heart rate were much more important than the experimental conditions.

Key Takeaways

  • Random effects can be used to analytically adjust estimates to account for known sources of structure in the data
  • An intuitive application is longitudinal data, because you’d anticipate some people are just healthier than other people, for whatever reasons
  • Random effects can be used for other sources of structure, such as hospital IDs, patient IDs, or aspects of the data collection protocol
  • The interpretation of results will look similar with and without random effects, but including random effects can help mitigate threats to validity
  • A limitation in using random effects is that they are more complicated models, which can make it more difficult for the computer to find a credible solution

Final Thoughts

Thank you again for participating in Practical Statistics! This documentation sheet is by no means a complete record of every approach you could use for every statistic you could calculate, but that also isn’t the intention. Computers have made it much easier to obtain many statistics with the push of a button, but that also serves as a distraction because some of these statistics won’t be relevant to every application! This program has been designed to help you gather your thoughts and connect it to data. Starting with theory, what is the context on the project, what big picture goals of why you undertook this body research? One project won’t be able to test everything within a theory, but what novel aspect do you want to emphasize, and how can it be formulated conceptually as a scientific hypothesis? Focusing now on the data you have available, what specific similarities and differences do you anticipate which could be numerically tested as a hypothesis? And what is the preliminary assumption you’re willing to make to evaluate this testable hypothesis, the null hypothesis you hope to rule out should there be enough evidence? Lastly, what are the threats to validity, questions you can’t completely answer in this project, but you could try to account for in the analysis? One size does not fit all in science, but thinking through these questions can be used to help connect the dots while you are formulating an analysis plan. And if you’re having trouble with it, don’t hesitate to reach out!

jtanzer@lifespan.org

joshua_tanzer@brown.edu