Error in 1 - diaghat : non-numeric argument to binary operator - r

I wanto to run a two way fixed effects model and then correct standard errors.
mod3 = plm(Dir ~ Dist +Trade + GDP_sim +GDP +
GDP_capita_constant +Openess + GDP_g + Endowments +
US_PTA + Japan_PTA + FDI + Population+ Democracy+Rule_of_Law+Values+sim+
WTO, data= dfPTA, index = c("Country", "Year"),
model = "within",
effect = "twoway")
this works very well.
However, when running this line
m.2wfe.scc <- coeftest(mod3, vcov = vcovSCC(mod3, type = "HC3", cluster = "group"))
I get the following error message
Error in 1 - diaghat : non-numeric argument to binary operator
All my variables are either numeric or integers (except Country).
Interestingly, I can run
mod4 = plm(Dir ~ Dist + Trade + GDP_sim +GDP +
GDP_capita_constant+Population+FDI, data= dfPTA, index = c("Country", "Year"),
model = "within",
effect = "twoway")
m.2wfe.scc <- coeftest(mod4, vcov = vcovSCC(mod4, type = "HC3", cluster = "group"))
and it works. Alltough I dont see a difference between the subset variables and the full model.
Any ideas?

Related

ADD INTERCEPT TO GMM MODEL IN R (function: pgmm; package: plm)

When I launch the pgmm function using the plm package for my dynamic panel data model I can see the output that shows the results for every variable I inserted in the model (including the lags) but I cannot see the results for the intercept.
Here is my code:
z1.AB <- pgmm(cpi ~ lag(cpi, 1:1)+lag(gdppc, 2:2) + lag(expense, 3:3) + lag(freedom, 2:2) | lag(cpi, 1:10) + lag(gdppc, 1:9) + lag(expense, 1:2) + lag(freedom, 1:8) + lag(democracy, 4:10) + lag(stability, 1:10),
data = model,
effect = "twoways",
model = "twosteps",
collapse = TRUE,
subset = sample == 1)
mtest(z1.AB, order = 1L)
mtest(z1.AB, order = 2L, vcov = vcovHC)
summary(z1.AB, robust = FALSE)
sargan(z1.AB)
Here is my output:
Please help me to put also the intercept in order to let it show with other variables in the output :(
I wanted to get my intercept together with other variables but it does not show.

Comparison between configural and metric model (MI) using semTools

I try to analyze for measurement invariance with multi groups (8 groups; group = "stort"). Below you can see my syntax. The wb variables are all ordinal, ranging from 1-5. There are 8 different groups: n1 =233, n2= 832 n3=67 n4=68 n5=530 n6=169 n7=139 n8=108
The following error occurs: If I try to compare the configural and the metric model using semTools (see syntax) I get an error message: Error in A %*% P.inv : requires numeric/complex matrix/vector arguments (also if I use lavTestLRT()). Other model comparisons run without any errors.
My question is, how can I fix this? I appreciate all comments :)
Here, you can find the dataset: https://drive.google.com/drive/folders/1h9hpFoRhz-zphJ3NSfXtDxbWoad3CmQI?usp=sharing
This is my model:
modelwb.1<- 'kaw =~ wb1.1 + wb2.1 + wb3.1invers + wb4.1invers
paw =~ wb5.1 + wb6.1 + wb7.1invers + wb8.1invers
saw =~ wb9.1 + wb10.1 + wb11.1invers + wb12.1invers
kaw ~ paw + saw
paw ~ saw
kaw ~~ paw + saw
paw ~~ saw
'
fitwb.1 <- cfa(modelwb.1, data=df_wide, estimator = "WLSMV")
summary(fitwb.1, fit.measures = TRUE, standardized = TRUE)
#### Configural model
fitwbcon.1 <- cfa(modelwb.1, data = df_wide, group = "stort", estimator = "WLSMV", missing = "pairwise")
summary(fitwbcon.1, fit.measures = TRUE, standardized = TRUE)
#### Metric model
fitwbmet.1 <- cfa(modelwb.1, data = df_wide, group = "stort", estimator = "WLSMV", missing = "pairwise", group.equal = "loadings")
summary(fitwbmet.1, fit.measures = TRUE, standardized = TRUE)
##### Model comparison: configural & metric
x1<- semTools::compareFit(fitwbcon.1, fitwbmet.1)
summary(x1)
##or:
lavTestLRT(fitwbcon.1, fitwbmet.1)

Why is gamm returning the error "unused argument (offset= ...)"?

all-
First-time poster, here, so please be forbearing if I've violated some of the conventions for asking questions (like, for example, providing a replicable example).
I'm trying to estimate a Generalized Additive Mixed Model using the "gamm" function with this code:
fit1.1 = gamm(opioidNonFatalOD ~ s(mandatoryReg.l2, k = 3, fx = TRUE,
bs = "cr") +
s(coalitionActive.l2, k = 3, fx = TRUE, bs = "cr") +
monthsSinceJan2011 +
everFunded +
ICD10 +
spoke5 +
hub +
s(monthly2, bs = "cc", fx = FALSE, k = 4) +
s(county2, bs = "re"),
#+ offset(log(population / 100000)),
correlation = corAR1(form = ~ monthsSinceJan2011 | county2),
data = tsData,
family = quasipoisson, offset = log(population / 100000),
niterPQL = 20,
verbosePQL = TRUE)
For some reason, it looks like the "offset" argument isn't getting passed to gammPQL. I get this error:
iteration 1
Quitting from lines 201-220 (pfs_model_experiments_041520.Rmd)
Error in lme(fixed = fixed, random = random, data = data, correlation = correlation, :
unused argument (offset = log(population/1e+05))
Calls: <Anonymous> ... withVisible -> eval -> eval -> gamm -> eval -> eval -> gammPQL
Execution halted
Here're the traceback messages:
Error in lme(fixed = fixed, random = random, data = data, correlation = correlation, : unused argument (offset = log(population/1e+05))
4.
gammPQL(y ~ X - 1, random = rand, data = strip.offset(mf), family = family, correlation = correlation, control = control, weights = weights, niter = niterPQL, verbose = verbosePQL, mustart = mustart, etastart = etastart, ...) at <text>#1
3.
eval(parse(text = paste("ret$lme<-gammPQL(", deparse(fixed.formula), ",random=rand,data=strip.offset(mf),family=family,", "correlation=correlation,control=control,", "weights=weights,niter=niterPQL,verbose=verbosePQL,mustart=mustart,etastart=etastart,...)", sep = "")))
2.
eval(parse(text = paste("ret$lme<-gammPQL(", deparse(fixed.formula), ",random=rand,data=strip.offset(mf),family=family,", "correlation=correlation,control=control,", "weights=weights,niter=niterPQL,verbose=verbosePQL,mustart=mustart,etastart=etastart,...)", sep = "")))
1.
gamm(opioidNonFatalOD ~ s(mandatoryReg.l2, k = 3, fx = TRUE, bs = "cr") + s(coalitionActive.l2, k = 3, fx = TRUE, bs = "cr") + monthsSinceJan2011 + everFunded + ICD10 + spoke5 + hub + s(monthly2, bs = "cc", fx = FALSE, k = 4) + s(county2, bs = "re"), ...
I've tried using the offset as a term in the model (see commented-out code), but get a similar error.
Just be inspecting the code, does anyone have an idea of what I'm doing wrong?
Thanks,
David
tl;dr;
Create the offset outside the gamm function and then pass it to the formula using ...+offset().
In your example then use:
tsData$off = log(tsData$population/100000)
gamm(opioidNonFatalOD ~ <other variables> + s(county2, bs = "re") + offset(off),
<other stuffs>)
The general syntax for gams to add an offset is to include it in the formula, like y ~ ... + x + offset(offset_variable). However, as seen in the examples below it seems as if gammis struggling to parse functions (i.e. the log or division) within the offset function.
Some examples:
library(mgcv)
# create some data
set.seed(1)
dat <- gamSim(6,n=200,scale=.2,dist="poisson")
# create an offset
dat$off1 = (dat$y+1)*sample(2:10, 200, TRUE)
Attempt 1: finds off1 but errors likely due to the large values in off1 (and we really would like the log transfromed, or whichever link function was used)
m1 <- gamm(y~s(x0)+s(x1)+s(x2) + offset(off1),
family=poisson,data=dat,random=list(fac=~1))
Maximum number of PQL iterations: 20
iteration 1
iteration 2
Show Traceback
Rerun with Debug
Error in na.fail.default(list(Xr.1 = c(-0.00679246534326368, -0.0381904761033802,
:missing values in object
Attempt 2: can't seem to find off1 after log transform within offset function
m2 <- gamm(y~s(x0)+s(x1)+s(x2) + offset(log(off1)),
family=poisson, data=dat,random=list(fac=~1))
Maximum number of PQL iterations: 20
iteration 1
Show Traceback
Rerun with Debug
Error in eval(predvars, data, env) : object 'off1' not found
Attempt 3: define offset term outside offset function
# Success
dat$off2 = log(dat$off1)
m3 <- gamm(y~s(x0)+s(x1)+s(x2) + offset(off2),
family=poisson, data=dat, random=list(fac=~1))
So create the offset variable outside then pass it to the gamm formula.

Undefined columns selected in mediate R

I'm currently facing a problem estimating the mediation effect with function mediate from R package mediation.
I'm running three panel regressions with plm from R package plm:
TERR1_us <- plm(log(POLSTAB+1) ~ log(US+1) + RDURAB + DEMOC + log(POP+1) +MUS, data = US, index = c('NUMBER', "YEAR"), model = 'within', effect = "individual")
TERR2_us<- plm(log(TERROR+1) ~ log(US+1) + RDURAB + DEMOC +log(POP+1)+ MUS, data = US, index = c('NUMBER', "YEAR"), model = 'within', effect = "individual")
TERR3_us <- plm(log(POLSTAB+1) ~ log(US+1) + RDURAB + DEMOC +log(POP+1)+MUS +log(TERROR+1), data = US, index = c('NUMBER', "YEAR"), model = 'within', effect = "individual")
To test the mediations significancy I run a bootstrapping test.
results_terr_us <- mediate(TERR2_us, TERR_us, treat="US", mediator="TERR",
boot=TRUE, sims=100)
Unfortunately, I always get the error message Error in [.data.frame(x, , "US") : undefined columns selected
Both models have the same number of observations. I don't think there are any commas that I set wrong.

Can the boxTidwell function handle binary outcome variables?

I initially wanted to run a boxTidwell() (found in the "car" package) analysis on my prospective Logistic Regression model (BinaryOutcomeVar ~ ContinuousPredVar + ContinuousPredVar^2 + ContinuousPredVar^3). I ran into issues:
Error in x - xbar : non-numeric argument to binary operator
In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA
So, I created a reproducable example for demonstrating the error:
Doesn't work:
boxTidwell(formula = Treatment ~ uptake, other.x = ~ poly(x = colnames(CO2)[c(1,2,4)], degree = 2), data = CO2)
boxTidwell(y = CO2$Treatment, x = CO2$uptake)
Works:
boxTidwell(formula = prestige ~ income + education, other.x = ~ poly(x = women , degree = 2), data = Prestige)
I've been goofing around with the other.x parameter and am guessing that's the issue.
Question
So, does anyone know if 1. the boxTidwell() function works with binary outcome variables 2. the logic behind the other.x, because I can't get my dummy example to work either.
After further searching, it looks like the car:::boxTidwell can't handle the binary outcome variable in the formula, but it can be hand coded:
require(MASS)
require(car)
d1<-read.csv("path for your csv file",sep=',',header=TRUE)
x<-d1$explanatory variable name
y<-d1$dependent variable name
#FIT IS DONE USING THE glm FUNCTION
m1res <- glm(y ~ x,family=binomial(link = "logit"))
coeff1<- coefficients(summary(m1res))
lnx<-x*log(x)
m2res <- glm(y ~ x+lnx ,family=binomial(link = "logit"))
coeff2<- coefficients(summary(m2res))
alpha0<-1.0
pvalue<-coeff2[3,4]
pvalue
beta1<-coeff1[2,1]
beta2<-coeff2[3,1]
iter<-0
err<-1
while (pvalue<0.1) {
alpha <-(beta2/beta1)+alpha0
err<-abs(alpha-alpha0)
alpha0<-alpha
mx<-x^alpha
m1res <- glm(y ~ mx,family=binomial(link = "logit"))
coeff1<- coefficients(summary(m1res))
mlnx<-mx*log(x)
m2res <- glm(y ~ mx+mlnx ,family=binomial(link = "logit"))
coeff2<- coefficients(summary(m2res))
pvalue<-coeff2[3,4]
beta1<-coeff1[2,1]
beta2<-coeff2[3,1]
iter<- iter+1
}
# PRINT THE POWER TO CONSOLE
alpha
above code taken from:
https://sites.google.com/site/ayyalaprem/box-tidwelltransform

Resources