matthiash
matthiash

Reputation: 3233

A concise way to extract some elements of a "survfit" object into a data frame

I load a data set from the survival library, and generate a survfit object:

library(survival)
data(lung)
lung$SurvObj <- with(lung, Surv(time, status == 2))
fit <- survfit(SurvObj ~ 1, data = lung, conf.type = "log-log")

This object is a list:

> str(fit)
List of 13
 $ n        : int 228
 $ time     : int [1:186] 5 11 12 13 15 26 30 31 53 54 ...
 $ n.risk   : num [1:186] 228 227 224 223 221 220 219 218 217 215 ...
 $ n.event  : num [1:186] 1 3 1 2 1 1 1 1 2 1 ...
 ...

Now I specify some members (all same length) that I want to turn into a data frame:

members <- c("time", "n.risk", "n.event") 

I'm looking for a concise way to make a data frame with the three list members as columns, with the columns named time, n.risk, n.event (not fit$time, fit$n.risk, fit$n.event)

Thus the resulting data frame should look like this:

           time     n.risk       n.event
  [1,]        5        228             1
  [2,]       11        227             3
  [3,]       12        224             1
  ...

Upvotes: 3

Views: 2861

Answers (4)

user6571411
user6571411

Reputation: 2979

The broompackage contains functions to tidy up the results of regression models and present them in an object of class data.frame. For those unfamiliar with the tidy philosophy, please see Tidy data [ 1 ]

library(broom)
#create tidy dataframe and subset by the columns saved in members
df <- tidy(fit)[,members]
head(df)
#  time n.risk n.event
#1    5    228       1
#2   11    227       3
#3   12    224       1
#4   13    223       2
#5   15    221       1
#6   26    220       1

[ 1 ] Wickham, Hadley . "Tidy Data." Journal of Statistical Software [Online], 59.10 (2014): 1 - 23. Web. 16 Jun. 2017

Upvotes: 3

Zheyuan Li
Zheyuan Li

Reputation: 73315

This is OK

data.frame(unclass(fit)[members])

Another (more canonical) way is

with(fit, data.frame(time, n.risk, n.event))

Upvotes: 6

midhunxavier
midhunxavier

Reputation: 66

library(survival)
data(lung)
lung$SurvObj <- with(lung, Surv(time, status == 2))
fit <- survfit(SurvObj ~ 1, data = lung, conf.type = "log-log")
str(fit)
members<-data.frame(time=fit$time,n.risk=fit$n.risk,n.event=fit$n.event)
members

Upvotes: 0

Ajay Ohri
Ajay Ohri

Reputation: 3492

Used cbind to bind the dataframes, then used names to change the name of columns

        time=as.data.frame(fit$time)
        n.risk=as.data.frame(fit$n.risk)
        n.event=as.data.frame(fit$n.event)
        members2=cbind(time,n.risk,n.event)
        names(members2)=c("time","n.risk","n.event")
     head(members2)
      time n.risk n.event
    1    5    228       1
    2   11    227       3
    3   12    224       1
    4   13    223       2
    5   15    221       1
    6   26    220       1

Upvotes: 0

Related Questions