eva_utrecht
eva_utrecht

Reputation: 95

"Object not found" error within a user defined function, eval() function?

I'm trying to write a function for a task I need to do many times (running a cox proportional hazards function over multiple imputed datasets). When I pass the necessary objects to my user-defined function, however, it gives an error, stating that the object cannot be found. I think this is because the object is defined within a dataframe that is specified with the "data=" argument within the cch() function. Can anyone help me with this?

Example data:

my.list<-list(my.df1 <- data.frame(my.id = 1:100, my.time = rlnorm(100), 
my.event= c(rbinom(50,1,0.2),rep(1,50)), my.det=rbinom(100,1,0.5), 
sub= c(rep(1,50), rbinom(50, 1, 0.1))),  my.df2 <- data.frame(my.id = 1:100, 
my.time = rlnorm(100), my.event= c(rbinom(50,1,0.2),rep(1,50)), 
my.det=rbinom(100,1,0.5), sub= c(rep(1,50), rbinom(50, 1, 0.1))))

Outside my user-defined function, this works:

library(KMsurv)
library(survival)
cch(Surv(my.time,my.event)~as.factor(my.det), data=my.df1, subcoh=~sub, 
id=~my.id, cohort.size=500)

However, this does not work (this is an example function, not the real function as the real function is more complex and runs analyses on multiple datasets, then combines them):

myfun<-function(dflist,time,event){
for (i in 1:length(dflist)){
out<-cch(Surv(time,event)~as.factor(my.det), data=dflist[[i]], 
subcoh=~sub, id=~my.id, cohort.size=500)
print(out)}
}   
myfun(my.list,my.time,my.event)

I get this error: "Error in Surv(time, event) : object 'my.time' not found".

I found some posts about using an eval(substitute()) function to deal with a similar problem, but I can't get it to work. Any suggestions are greatly appreciated!

Upvotes: 2

Views: 25284

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

Try this. You need to keep in mind that R doesn't know what's my.time and my.event. You have to parse them with quotes and then unqoute them in order to parse it into Surv

myfun<-function(dflist,time,event){
  for (i in 1:length(dflist)){
    time <- noquote(time)
    event <- noquote(event)
    out<-cch(Surv(dflist[[i]][, time], dflist[[i]][, event])~as.factor(my.det), data=dflist[[i]], 
             subcoh=~sub, id=~my.id, cohort.size=500)
    print(out)}
}   
myfun(my.list,"my.time","my.event")

Upvotes: 3

Related Questions