############################################
# EXAMPLE 1
# Using the Jessor data discussed in Preacher and Kelley (2011), to illustrate
# the methods based on summary statistics. 
 
mediation(S=rbind(c(2.26831107,  0.6615415, -0.08691755), 
c(0.66154147,  2.2763549, -0.22593820), c(-0.08691755, -0.2259382,  0.09218055)), 
N=432, x.location.S=1, mediator.location.S=2, dv.location.S=3, mean.x=7.157645, 
mean.m=5.892785, mean.dv=1.649316, conf.level=.95)
############################################
# EXAMPLE 2
# Clear the workspace:
rm(list=ls(all=TRUE))
# An (Unrealistic) example data (from Hayes) 
Data <- rbind(
  c(-5.00, 25.00, -1.00),
  c(-4.00, 16.00, 2.00),
  c(-3.00, 9.00, 3.00),
  c(-2.00, 4.00, 4.00),
  c(-1.00, 1.00, 5.00),
  c(.00, .00, 6.00),
  c(1.00, 1.00, 7.00),
  c(2.00, 4.00, 8.00),
  c(3.00, 9.00, 9.00),
  c(4.00, 16.00, 10.00),
  c(5.00, 25.00, 13.00),
  c(-5.00, 25.00, -1.00),
  c(-4.00, 16.00, 2.00),
  c(-3.00, 9.00, 3.00),
  c(-2.00, 4.00, 4.00),
  c(-1.00, 1.00, 5.00),
  c(.00, .00, 6.00),
  c(1.00, 1.00, 7.00),
  c(2.00, 4.00, 8.00),
  c(3.00, 9.00, 9.00),
  c(4.00, 16.00, 10.00),
  c(5.00, 25.00, 13.00))
# "Regular" example of the Hayes data.
mediation(x=Data[,1], mediator=Data[,2], dv=Data[,3], conf.level=.95)
# Sufficient statistics example of the Hayes data.
mediation(S=var(Data), N=22, x.location.S=1, mediator.location.S=2, dv.location.S=3, 
mean.x=mean(Data[,1]), mean.m=mean(Data[,2]), mean.dv=mean(Data[,3]), conf.level=.95)
# Example had there been two groups. 
gp.size <- length(Data[,1])/2 # adjust if using an odd number of observations.
grouping.variable <- c(rep(0, gp.size), rep(1, gp.size))
mediation(x=grouping.variable, mediator=Data[,2], dv=Data[,3])
############################################
# EXAMPLE 3
# Bootstrap of continuous data. 
set.seed(12414) # Seed used for repeatability (there is nothing special about this seed)
bs.Results <- mediation(x=Data[,1], mediator=Data[,2], dv=Data[,3], 
bootstrap=TRUE, B=5000, save.bs.replicates=TRUE)
ls() # Notice that Bootstrap.Replicates is available in the 
workspace (if save.bs.replicates=TRUE in the above call). 
#Now, given the Bootstrap.Replicates object, one can do whatever they want with them. 
# See the names of the effect sizes (and their ordering)
colnames(Bootstrap.Replicates)
# Define IE as the indirect effect from the Bootstrap.Replicates object. 
IE <- Bootstrap.Replicates$Indirect.Effect
# Summary statistics
mean(IE)
median(IE)
sqrt(var(IE))
# CIs from percentile perspective
quantile(IE, probs=c(.025, .975))
# p-value. 
mean(IE>0)
Run the code above in your browser using DataLab