Background Information
I have been running mediation analysis using the mediate
function available in the R Mediation Package by Tingley et. al. I have run this package on a series of iterations of regressions, and it has left me with approximately 50 mediation objects.
Unfortunately, the mediation
package does not seem to have an easy way to export the summaries of these objects, and it is not supported by stargazer
. Therefore, I figured that I would try to extract the desired information from these objects myself and package them into a data frame.
What I want to do
I want to extract specific components from each mediation object and insert them as a row into a new data frame. This is what I want the data to look like:
MEDIATION ACME ACME 95H ACME95L ACMEP ... N.OBS
Mediation 1 0.809 1.201 0.756 0.02 ... 3154
Mediation 2 0.765 0.829 0.711 0.05 ... 3154
Mediation 3 0.050 0.159 -0.056 0.76 ... 3154
I have searched through the mediation objects and found the corresponding components for each of the items that I would like to extract. My thinking was that I would use a loop to generate a dataset that would assign each mediation object a single row, and would array the specified data in wide form.
Reproducible Example
Below is a reproducible version of running the basic mediation. For the sake of example, I use the swiss
data, which are pre-packaged with R.
# Use `swiss` data
summary(swiss)
# use `mediation` package
library(mediation)
# Run the regression for the IV effect on mediator
med.m <- lm(Catholic ~ Education, data = swiss)
# Run the regression for the full model, including mediator
med.y <- lm(Infant.Mortality ~ Education + Catholic, data = swiss)
# Run the mediation analysis, with the IV set as "Education and the mediator set as "Catholic"
Mediation.1<- mediate(med.m, med.y, sims = 1000, treat = "Education", mediator = "Catholic")
# Inspect the Mediation
summary(medsummary)
Here is what I tried to do when extracting the components of the mediation object:
# Create a list of the mediations
mediations <- c("Mediation.1", "Mediation.2", "Mediation.3", ..., "Mediation 50")
# Create an empty data frame
med.df <- data.frame(matrix(NA, nrow = 51, ncol = 20))
# Loop through data and extract components
for (c in seq(1:51)){
for (i in mediations){
med.df[c,] <- c("i", i[[1]]1, i[[3]][1], i[[3]][2], i[[5]][1], [[92]])
}
}
Unfortunately, this just results in the data frame looking like this:
1 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1
2 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1
3 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1 i Mediation.1
Would someone be willing to help me understand what I'm doing wrong, and how to fix this?
Thank you!