I think you're pretty close. If you create a function for doing the estimation, then you're just a few steps from getting your result.
I'm assuming you're using the package MSwM. Also, I don't have access to your data, so I'm using the energy data set included in MSwM.
library(MSwM)
data("energy")
I removed the prefix Port1 and the suffix Ill from your code and created a function that takes a model and extracts the relevant values as a named vector.
get_coeff <- function(msm) {
# Two variables to determine the greater and smaller coefficients
High <- ifelse(msm@Coef[1,]> msm@Coef[2,],msm@Coef[1,],
msm@Coef[2,])
Low <- ifelse(msm@Coef[1,] < msm@Coef[2,], msm@Coef[1,],
msm@Coef[2,])
# The associated probabilities
ProbLow <- ifelse(msm@Coef[1,] > msm@Coef[2,], msm@transMat[2,2],
msm@transMat[1,1])
ProbHigh <- ifelse(msm@Coef[1,] > msm@Coef[2,], msm@transMat[1,1],
msm@transMat[2,2])
# The main variable of interest
E <- Low * ProbLow + (High-Low) * ProbHigh
c(High = High,
Low = Low,
ProbHigh = ProbHigh,
ProbLow = ProbLow,
E = E
)
}
In the following section, I create a vector of variable names, which I convert them into a list of formulas, which I then I use to create a list of linear models. From this, I use lapply to create a list of msm models, from which I apply the function above, which gives me a list coefficient vectors.
vars <- c("Oil", "Gas", "Coal")
forms <- lapply(vars, function(v) as.formula(paste(v, '~ 1')))
lm_mods <- lapply(forms, function(f) lm(f, data = energy))
ms_mods <- lapply(lm_mods, function(m) msmFit(m, 2, sw = rep(TRUE,2)))
ms_coeff <- lapply(ms_mods, get_coeff)
The last step is to give each vector a name. This allows us to create a dataframe, which can be converted to a matrix.
names(ms_coeff) <- vars
as.matrix(as.data.frame(ms_coeff))