jmpsteen / medflex

Flexible mediation analysis using natural effect models in R
23 stars 6 forks source link

Problem with neWeight and neImpute: formula for model passed to neWeight can not be specific as variable #2

Closed jlegewie closed 8 years ago

jlegewie commented 8 years ago

Great package, great work!

I ran into some problems though that made it a hassle to get started with medflex. Here is one issue (creating a second issue for another problem).

The model passed to neWeight or neImpute has to be specific in a very particular way. Otherwise, I always run into this error: "Error in terms.formula(as.formula(x)) : argument is not a valid model". The difference between the examples below is how the formula is passed to the glm call. There is no reason why passing the formula as an object to glm should not work...

Thanks!

Works

medFit  <- glm(negaff ~ factor(attbin) + gender + educ + age, family = gaussian, data = UPBdata)
expData <- neWeight(medFit)

Does not work

f <- negaff ~ factor(attbin) + gender + educ + age
medFit  <- glm(f, family = gaussian, data = UPBdata)
expData <- neWeight(medFit)
f <- "negaff ~ factor(attbin) + gender + educ + age"
medFit  <- glm(as.formula(f), family = gaussian, data = UPBdata)
expData <- neWeight(medFit)
f <- "negaff ~ factor(attbin) + gender + educ + age"
medFit  <- glm(f, family = gaussian, data = UPBdata)
expData <- neWeight(medFit)
jmpsteen commented 8 years ago

Thanks for pointing this out! I have made some changes in order to maximally mimick glm's behavior. All of your examples should work now, as well as neImpute equivalents below:

f <- UPB ~ attbin + negaff + gender + educ + age
impFit  <- glm(f, family = binomial, data = UPBdata)
expData <- neImpute(impFit)
f <- "UPB ~ attbin + negaff + gender + educ + age"
impFit  <- glm(as.formula(f), family = binomial, data = UPBdata)
expData <- neImpute(impFit)
f <- "UPB ~ attbin + negaff + gender + educ + age"
impFit  <- glm(f, family = binomial, data = UPBdata)
expData <- neImpute(impFit)

In addition, I've added some changes so that the different formula characterizations can also be directly be used in neWeight. The first two already worked, but the last example returned an error in version 0.6-0.

f <- negaff ~ factor(attbin) + gender + educ + age
expData <- neWeight(f, family = gaussian, data = UPBdata)
f <- "negaff ~ factor(attbin) + gender + educ + age"
expData <- neWeight(as.formula(f), family = gaussian, data = UPBdata)
f <- "negaff ~ factor(attbin) + gender + educ + age"
expData <- neWeight(f, family = gaussian, data = UPBdata)

neImpute equivalents:

f <- UPB ~ attbin + negaff + gender + educ + age
expData <- neImpute(f, family = binomial, data = UPBdata)
f <- "UPB ~ attbin + negaff + gender + educ + age"
expData <- neImpute(as.formula(f), family = binomial, data = UPBdata)
f <- "UPB ~ attbin + negaff + gender + educ + age"
expData <- neImpute(f, family = binomial, data = UPBdata)