[R] Some seemingly odd behavior of survfit in library survival
Heinz Tuechler
tuech|er @end|ng |rom gmx@@t
Tue Mar 17 07:10:09 CET 2020
Jeff Newmiller wrote/hat geschrieben on/am 17.03.2020 05:39:
> The coxph function appears to rely on finding the name of the data argument in the environment in which the formula was created. The lm function does not have this problem.
>
> Oh, and df is the name of the F distribution density function, which explains why the error complained about a "closure".
>
> new<-as.data.frame(list(t=1:4,d=rep(1,4),s=c(1,0,0,1)))
> library(survival)
> mine<-function(ff,df){
> fit<-coxph(as.formula(ff),data=df)
> survfit(fit,df)
> }
> mine("Surv(t,d)~s",new)
>
Therefore a workaround could be to use the character string for the
formula as argument and apply as.formula() within the function.
mine2 <-function(fstr,df){
fit<-coxph(as.formula(fstr),data=df)
out<-survfit(fit,df)
out
}
mine2("Surv(t,d)~s",new)
Heinz
>
> On March 16, 2020 7:23:26 PM PDT, John Kolassa <kolassa using stat.rutgers.edu> wrote:
>> I ran across an issue that looks like variable scoping in survfit is
>> not acting as I would expect. Here's a minimal example:
>>
>> new<-as.data.frame(list(t=1:4,d=rep(1,4),s=c(1,0,0,1)))
>> library(survival)
>> mine<-function(ff,df){
>> fit<-coxph(ff,data=df)
>> out<-survfit(fit,df)
>> }
>> mine(as.formula("Surv(t,d)~s"),new)
>>
>> I would expect this to fit the proportional hazards regression model
>> using formula Surv(t,d)~s, using data set new, and then calculate a
>> separate fitted survival curve for each member of the data set.
>> Instead I get an error
>>
>> Error in eval(predvars, data, env) :
>> invalid 'envir' argument of type 'closure'
>>
>> The code runs without error if I modify it by copying the data set new
>> to the local variable within the function mine before running:
>>
>> new<-as.data.frame(list(t=1:4,d=rep(1,4),s=c(1,0,0,1)))
>> library(survival)
>> mine<-function(ff,df){
>> fit<-coxph(ff,data=df)
>> out<-survfit(fit,df)
>> }
>> df<-new
>> mine(as.formula("Surv(t,d)~s"),new)
>>
>> which leads me to believe that there's some variable scoping error.
>> Can anyone point out what I'm doing wrong? Thanks, John
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list