I have a multiply imputed dataset of class mids. I use the with() function to estimate the m different datasets with the coxph() function. However, I'm having trouble using the with() function within my own function.
The code below is a simplified example that reproduces the error: Error in Surv(enter,exit,event) object 'enter' not found
list<-"X1+X2"
var.used<-formula(paste("Surv(enter,exit,event)~",list,sep=""))
with.coxph<-function(form,dataset){
with(dataset,coxph(form))
}
with.coxph(var.used,data)
When I simply run the function on its own:
with(dataset, coxph(Surv(enter,exit,event)~X1+X2))
It works fine.
I think the problem is related to the environment where with() is called. I found different posts in here, but I can't seem to make it work. I tried assigning the dataset and the formula to the global environment:
with.coxph2<-function(form,dataset){
assign(".dataset",dataset,envir=.GlobalEnv)
assign(".form",dataset,envir=.GlobalEnv)
with(dataset,coxph(form))
remove(".dataset",dataset,envir=.GlobalEnv)
remove(".form",dataset,envir=.GlobalEnv)
}
with.coxph2(var.used,data)
but this produced the same error.
EDIT
I have attempted to fix the problem as described below. When i simply run the function with out the with() statement it works perfectly.
makeModel<-function(resp, explan, mData) {
mF <- formula(paste(resp, paste(explan, collapse = "+"), sep = "~"))
mod <- coxph(mF, data = mData)
mod$call$formula <- mF
mod$call$data <- as.symbol(deparse(substitute(mData)))
mod
}
cp <- makeModel("Surv(start, stop, event)", "X1", complete(data))
# This works fine
However, I still get the same error when I include the with() statement in the equation:
with.coxph<-function(resp, explan, mData) {
mF <- formula(paste(resp, paste(explan, collapse = "+"), sep = "~"))
mod <- with(mData,coxph(mF))
mod$call$formula <- mF
mod$call$data <- as.symbol(deparse(substitute(mData)))
mod
}
cp <- with.coxph("Surv(start, stop, event)", "X1", data)
# Error in Surv(enter,exit,event): object 'enter' not found