Skip to content

Instantly share code, notes, and snippets.

@PhilipPallmann
Last active August 29, 2015 14:03
Show Gist options
  • Save PhilipPallmann/a2bab1e265155709f644 to your computer and use it in GitHub Desktop.
Save PhilipPallmann/a2bab1e265155709f644 to your computer and use it in GitHub Desktop.
Convert a survival dataset in wide format (with numbers of survivors in columns) to a list with variables 'time' and 'event' as required for survival analysis in R.
toSurv <- function(data, times){
if(ncol(data)!=length(times)){
stop("'data' and 'time' must be equal in length.")
}
last <- ncol(data)
eventlist <- timelist <- list()
for(r in 1:nrow(data)){
da <- as.numeric(data[r, ])
begin <- da[1]
end <- da[last]
dd <- numeric(length(da) - 1)
for(i in 2:length(da)){
dd[i] <- -1 * (da[i] - da[i - 1])
}
timelist[[r]] <- c(rep(times, dd), rep(last, end))
eventlist[[r]] <- c(rep(1, sum(dd)), rep(0, end))
}
return(list(time=unlist(timelist), event=unlist(eventlist)))
}
# A toy example
DATA <- rbind(c(20, 20, 19, 16, 15, 13, 11),
c(20, 19, 17, 15, 12, 11, 10),
c(20, 19, 17, 17, 13, 11, 9))
TIME <- 1:7
toSurv(DATA, TIME)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment