How to export 'flexmix' model (in R) into Tex? - r

I have used the R package 'flexmix' to create some regression models. I now want to export the results to Tex.
Unlike conventional models created with lm(), the flexmix models are not saved as named numerics but as FLXRoptim objects.
When I now use the normal syntax from the 'texreg' package in order to create Tex code from the model results, I am getting error messages:
"unable to find an inherited method for function ‘extract’ for signature ‘"FLXRoptim"’"
I have to access the models directly, these are stored as 'Coefmat' and I did not manage to make this usable for texreg().
library(flexmix)
library(texreg)
data("patent")
## 1. Flexmix model ##
flex.model <- flexmix(formula = Patents ~ lgRD, data = patent, k = 3,
model = FLXMRglm(family = "poisson"), concomitant = FLXPmultinom(~RDS))
re.flex.model <- refit(flex.model)
## 2. Approach of results extraction ##
comp1.flex <- re.flex.model#components[[1]][["Comp.1"]]
## 3. Not working: Tex Export ##
texreg(comp1.flex)
Do you guys have an idea how to make these model results usable for Tex export?

I have now found a workaround: 'Texreg' allows us to create Texreg models with manually specified columns.
createTexreg(coef.names, coef, se, pvalues)
Using the example from above:
## Take estimates, SEs, and p-values for Comp1 ##
est1 <- re.flex.model#components[[1]][["Comp.1"]][,1]
se1 <- re.flex.model#components[[1]][["Comp.1"]][,2]
pval1 <- re.flex.model#components[[1]][["Comp.1"]][,4]
## Take estimates, SEs, and p-values for Comp2 ##
est2 <- re.flex.model#components[[1]][["Comp.2"]][,1]
se2 <- re.flex.model#components[[1]][["Comp.2"]][,2]
pval2 <- re.flex.model#components[[1]][["Comp.2"]][,4]
## Create Texreg objects and export into Tex ##
mymodel1 <- createTexreg(row.names(comp1.flex), est1, se1, pval1)
mymodel2 <- createTexreg(row.names(comp1.flex), est2, se2, pval2)
models.flex = list(mymodel1, mymodel2)
texreg(models.flex)
That's probably the most practical way to turn such specific models into a conventional Tex output.

Related

Flexmix package in R - extracting from Flexmix output object into dataframe

I have output from a 2-component mixture model run using the Flexmix package in R. I am trying to extract the list of model coefficients, which is stored in what seems to be a list(mix2#components$Comp.1) inside an object of "Formal class FLXcomponent". I would like to store the estimates from each component ins separate dataframes.
### Simulated data for regression mixture model using Flexmix
### Class 1
x<-seq(from=1,to=2, by=0.01)
y<-seq(from=0,to=1, by=0.01)
z<-x+y+y^2
class_label <- c(rep(c(1), length(z)))
dat1<-data.frame(x,y,z,class_label)
### Class2
x<-seq(from=2,to=3, by=0.01)
y<-seq(from=10,to=11, by=0.01)
z<-x^2+y+y^2
class_label <- c(rep(c(2), length(z)))
dat2<-data.frame(x,y,z,class_label)
simdat<-rbind(dat1,dat2)
### Run the model
mix2 <- flexmix(z ~ x+y+x^2+y^2, data=simdat, k=2)
out2<-summary(mix2)
out2
### Extract model coefficients for Component 1
mix2#components$Comp.1
str(mix2#components$Comp.1)
mix2#components[[1]][["Comp.1"]][,1]
mix2#components$Comp.1[,1]
I tried using the getSlots() function in R on mix2, but this gives an error:
getSlots(mix2#components$Comp.1)
Error in .getClassesFromCache(Class) :
class should be either a character-string name or a class definition
How can I extract the coefficients in the model components and save them in a dataframe?
For instance, neither of the approaches below works:
outdat<-as.data.frame(mix2#components[[1]][["Comp.1"]][,1])
outdat<-as.data.frame(mix2#components$Comp.1)
This seems to work, although I am open to other (better) approaches.
mix2 <- flexmix(z ~ I(x^2)+I(y^2), data=simdat, k=2)
p1<-parameters(mix2, component=1)[[1]]
p2<-parameters(mix2, component=1)[[2]]
and so on.

Extract Regression Tables from R Studio to Lyx for research paper

Im working on a project that im searching what the effects of Risk-Taking behaviour on Entrepreneurship, i mean how culture affects the Entrepreneurial activities. I run regressions to see the impact of independent variables on the dependent variables which represent the presence of Entrepreneurial Intention.
I would like to exctract the regression tables and summary tables i have constructed to the LyX document processor in order to have a more scientific view.
Whats the process i must follow to do this ??
EDIT:
MY DATASET:
My dataset is quite big and even if i use the order: dput(head(GemData,10)) the result is very big to post it here !!! Any order way ?!
MY CODE:
## you need the 'haven' package for loading a .dta file
library(haven)
GemData <- read_dta(("C:/Users/ILIAS/Documents/Bachelors Thesis/GEM Dataset.dta"))
#### Stepwise Regression for y1 = 'all_high_stat_entre' and y2 = 'all_fear_fail' ####
library(MASS)
index<-which(is.na(GemData$all_high_stat_entre)==F)
n = nrow(GemData)
r<-NULL
for(i in 2:n){
r[i-1]=cor(GemData$all_high_stat_entre[index],GemData[index,i])
}
index.r<-which(is.na(r)==F)
## 'res' is that number of column which the response 'all_high_stat_entre' ##
res = which(r==1)
#---------------------------------------------------------------------------------------
index_fail<-which(is.na(GemData$all_fear_fail)==F)
r_fail<-NULL
for(i in 2:n){
r_fail[i-1]=cor(GemData$all_fear_fail[index_fail],GemData[index_fail,i])
}
index.r.fail<-which(is.na(r_fail)==F)
## 'res.fail' is that number of column which the response 'all_fear_fail' ##
res.fail = which(r_fail==1)
#### Stepwise regression of 'all_high_stat_entre' ####
index.r.mod = index.r[-res]
index.r.mod.1=which(abs(r)>0.3)
n.all_high = length(index.r.mod.1)
data.subset=GemData[index,index.r.mod.1]
data.subset[,(n.all_high + 1)]=GemData$all_high_stat_entre[index]
colnames(data.subset)=c(names(data.subset)[1:19],"all_high_stat_entre")
## fit a full model
full.model <- lm(all_high_stat_entre~.,data=data.subset)
min.model <- lm(all_high_stat_entre~1,data=data.subset)
## ols_step_all_possible(full.model)
library(olsrr)
ols_step_forward_p(full.model)
model.all.high = lm(all_high_stat_entre ~ all_entre_des+all_estab_bus_age2+all_est_bus_fem+all_fut_startbus+all_startbus_job+all_know_entre+all_est_bus_sect4,data=data.subset)
summary(model.all.high)
stargazer(model.all.high, title="Results",type='text')
fwd.model <- stepAIC(min.model, direction='forward', scope=(~all_entre_des+all_estab_bus_age2+all_est_bus_fem+all_fut_startbus+all_startbus_job+all_know_entre+all_est_bus_sect4),data=data.subset)
library(stargazer)
stargazer(fwd.model, title="Results",type='text')
#--------------------------------------------------------------------------------------------
#### Modeling for the response 'all_fear_fail' ####
index.r.mod.fail = index.r[-res.fail]
index.r.mod.fail.1=which(abs(r_fail)>0.3)
n.all_fail = length(index.r.mod.fail.1)
data.subset.fail=GemData[index_fail,index.r.mod.fail.1]
data.subset.fail[,(n.all_fail + 1)]=GemData$all_fear_fail[index_fail]
colnames(data.subset.fail)=c(names(data.subset.fail)[1:(n.all_fail)],"all_fear_fail")
## fit a full model
full.model.fail <- lm(all_fear_fail~.,data=data.subset.fail)
min.model.fail <- lm(all_fear_fail~1,data=data.subset.fail)
## ols_step_all_possible(full.model)
library(olsrr)
ols_step_forward_p(full.model.fail)
fwd.model.fail <- stepAIC(min.model.fail, direction='forward', scope=(~all_per_cap+all_know_entre+all_per_opp),data=data.subset.fail)
library(stargazer)
stargazer(fwd.model.fail, title="Results" , type='text')
Thanks in advance !

R Output of fGarch

I am modelling a time series as a GARCH(1,1)-process:
And the z_t are t-distributed.
In R, I do this in the fGarch-package via
model <- garchFit(formula = ~garch(1,1), cond.dist = "std", data=r)
Is this correct?
Now, I would like to understand the output of this to check my formula.
Obviously, model#fit$coefs gives me the coefficients and model#fitted gives me the fitted r_t.
But how do I get the fitted sigma_t and z_t?
I believe that the best way is to define extractor functions when generics are not available and methods when generics already exist.
The first two functions extract the values of interest from the fitted objects.
get_sigma_t <- function(x, ...){
x#sigma.t
}
get_z_t <- function(x, ...){
x#fit$series$z
}
Here a logLik method for objects of class "fGARCH" is defined.
logLik.fGARCH <- function(x, ...){
x#fit$value
}
Now use the functions, including the method. The data comes from the first example in help("garchFit").
N <- 200
r <- as.vector(garchSim(garchSpec(rseed = 1985), n = N)[,1])
model <- garchFit(~ garch(1, 1), data = r, trace = FALSE)
get_sigma_t(model) # output not shown
get_z_t(model) # output not shown
logLik(model)
#LogLikelihood
# -861.9494
Note also that methods coef and fitted exist, there is no need for model#fitted or model#fit$coefs, like is written in the question.
fitted(model) # much simpler
coef(model)
# mu omega alpha1 beta1
#3.541769e-05 1.081941e-06 8.885493e-02 8.120038e-01
It is a list structure. Can find the structure with
str(model)
From the structure, it is easier to extract with $ or #
model#fit$series$z
model#sigma.t

How to obtain coefficients' p-values from a nested random effect model using lmeresampler

I estimated a mixed effect model with a nested random effect structure (participants were in different groups) with the lmer command of the lme4 package.
mixed.model <- lmer(ln.v ~ treatment*level+age+income+(1 | group/participant),data=data)
Then I bootstrapped the bootstrap command from the lmeresampler package because of the nested structure. I used the semi-parametric bootstrap.
boot.mixed.model <- bootstrap(model = mixed.model, type = "cgr", fn = extractor, B = 10000, resample=c(data$group,data$participant))
I can obtain bootsrapped confidence intervals via boot.ci (package boot) but in addition I want to report the coefficients' p-values. The output of the bootstrapped model boot.mixed.model provides only the bias and the standard error:
Bootstrap Statistics :
original bias std. error
t1* 0.658442415 -7.060056e-02 2.34685668
t2* -0.452128438 -2.755208e-03 0.17041300
…
What is the best way to calculate the p-values based on these values?
I am unaware of the package called lmeresampler, and it seems to have been removed from cran due to compatibility issues (failed cran checks).
Also, the question does not include data and extractor is not defined, so the example is not reproducible. However the output is the same as you would get by using the bootMer function from lme4 so produce and example using the inbuilt function.
Basically this follows the example from the help(bootMer) page, but expanded for the specific problem. If the object returend by the lmeresampler package is similar, it will contain the objects used.
Reproducible example
library(lme4)
data(Dyestuff, package = "lme4")
fm01ML <- lmer(Yield ~ 1|Batch, Dyestuff, REML = FALSE)
Now the bootMer function simply requires a function, which outputs a vector of interesting parameters.
StatFun <- function(merMod){
pars <- getME(merMod, c("fixef", "theta", "sigma"))
c(beta = pars$fixef, theta = unname(pars$theta * pars$sigma), sigma = pars$sigma) ### <<== Error corrected
}
We can perform our bootstrapping by using the bootMer, which also contains parametric options in type (i suggest reading the details in the help(bootMer) page for more information)
boo01 <- bootMer(fm01ML, StatFun, nsim = 100, seed = 101)
Now for more precise p-values, I'd advice p-values greater closer to 1000 but for time reasons it might not be feasible in every circumstance.
Regardless the output is stored in a matrix t, which we can use to perform a simple Kolmogorov-supremum test:
H0 <- c(0, 0, 0)
Test <- sweep(abs(boo01$t), 2, H0, "-") <= H0 ###<<=== Error corrected
pVals <- colSums(Test)/nrow(Test)
print(pVals)
#output#
beta.(Intercept) theta sigma
0.00 0.12 0.00

Add p-value of Hausman test (or other additional GOF measure) to texreg table

I use texreg to report the results of several random effects models (estimated using plm) in a table.
How can I add the p-value of a Hausman test (comparing each model to its fixed effects counterpart) to the goodness-of-fit measures reported by texreg? More generally, how can I report additional goodness-of-fit measures with texreg?
Assuming you have a model object called model, you should follow three steps:
1) Execute tr <- extract(model) in order to create a texreg object.
2) Manipulate this texreg object. Example:
tr#gof <- c(tr#gof, 0.5)
tr#gof.names <- c(tr#gof.names, "new row")
tr#gof.decimal <- c(tr#gof.decimal, TRUE)
3) Execute your original texreg command, but include the tr object instead of the original model. Example: screenreg(tr).
If you think a GOF measure should be included in an extract method included in the texreg package by default, you should make suggestions in the texreg forum on R-Forge.
I found a way to add p-value of Hausman test (and other additional GOF measures) to texreg table. This method will fetch the GOF measures automatically so you do not have to do it manually. Ask if you have any questions.
Suppose that "random1" and "fixed1" are your models
First make the Hausman test into an object
ph1 <- phtest(random1, fixed1)
Then extract the coefficients of your model
sf1 <- summary(fixed1)
names1 <- rownames(sf1$coef)
co1 <- sf1$coef[, 1]
se1 <- sf1$coef[, 2]
pval1 <- sf1$coef[, 4]
Then extract your choice of GOFs
pval.ftest1 <- (summary(fixed1)$fstatistic)$p.value
rs1 <- sf1$r.squared
adj1 <- sf1$adj.r.squared
n1 <- nobs(fixed1)
phtest1 <- fp.value.fixed1
Choose which GOFs to include in the table
gof1 <- c(pval.ftest1, rs1, adj1, n1, phtest1)
gof.names1 <- c("p\\ (F-test)","R$^2$", "Adj.\\ R$^2$", "Num.\\ Obs.", "p\\ (Hausman\\ test)")
Choose decimal places for GOFs
decimal.places <- c(TRUE, TRUE, TRUE, FALSE, TRUE)
Create a texreg object
tr1 <- createTexreg(coef.names = names1, coef = co1, se = se1, pvalues = pval1, gof.names = gof.names1, gof = gof1, gof.decimal = decimal.places)
Check that everything looks OK with screenreg
screenreg(tr1)
Repeat the same thing for all of your models (fixed2, fixed3...& random2, random3...) if necessary.
Check that everything looks OK with all models before using texreg or htmlreg functions
screenreg(list(tr1, tr2, tr3, tr4, tr5))

Resources