r - "Object not found" error within a user defined function, eval() function? -
i'm trying write function task need many times (running cox proportional hazards function on multiple imputed datasets). when pass necessary objects user-defined function, however, gives error, stating object cannot found. think because object defined within dataframe specified "data=" argument within cch() function. can me 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 user-defined function, 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, not work (this example function, not real function real function more complex , runs analyses on multiple datasets, combines them):
myfun<-function(dflist,time,event){ (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 error: "error in surv(time, event) : object 'my.time' not found".
i found posts using eval(substitute()) function deal similar problem, can't work. suggestions appreciated!
try this. need keep in mind r doesn't know what's my.time
, my.event
. have parse them quotes , unqoute them in order parse surv
myfun<-function(dflist,time,event){ (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")
Comments
Post a Comment