0

I know how to draw survival curves (made by survival package) by autoplot from ggfortify. Here I use ovarian data frame, also from survival package.

library(survival)
library(ggfortify)

autoplot(survfit(Surv(ovarian$futime, ovarian$fustat) ~ ovarian$resid.ds))

It's possible to provide survfit function with column names only and specify data frame separately, as follows:

autoplot(survfit(Surv(futime, fustat) ~ resid.ds, data = ovarian))

This works nicely. What I would like to do is wrap it into my own function with data argument at the beginning, so that I could use pipes and filter my dataframe beforehands, without having to create gazillions new dataframes.

This is the function:

 myfun <- function(data, time, event, group){
      autoplot(survfit(Surv(time, event) ~ group, data))
 }

Calling it however raises an error:

myfun(ovarian, futime, fustat, resid.ds)

Error in Surv(time, event) : object 'futime' not found 

Am I missing something?

4

1 回答 1

1

I think I have it. Using subscripts to address columns works just fine.

myfun <- function(data, time, event, group){
  autoplot(survfit(Surv(data[,time], data[,event]) ~ data[,group]))
}


filter(ovarian, futime < 500) %>%
myfun("futime", "fustat", "resid.ds")

If you have more elegant or "right" solution, I'm all ears. :-)

于 2018-04-14T21:57:48.390 回答