cox.R 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #' COX hazards
  2. #'
  3. #' @param x data frame
  4. #' @param vars a vector of variables used in Cox's survival analysis
  5. #'
  6. #' @return model as returned by coxph
  7. #'
  8. #' @export
  9. cox.hazard<-function(x,vars){
  10. vlist=base::paste(vars,collapse='+')
  11. f<-stats::as.formula(base::paste('Surv(followup,censored)',vlist,sep='~'))
  12. s=survival::coxph(f,data=x)
  13. s
  14. }
  15. #' COX for univariate variables
  16. #'
  17. #' @param x data frame containing followup and censored columns
  18. #' @param var the variable used to explain survival in format mode:name where mode drives unitChange selection, SD for m, 1 for r or logic and X for uX
  19. #'
  20. #' @return data frame with a single row for tested variable, with fields variableName,unitChange,HR,l95,u95,pWald,pLikelihood
  21. #'
  22. #' @export
  23. cox.univariate<-function(x,var){
  24. data=base::c(var)
  25. qv=base::strsplit(data,split=':')[[1]]
  26. mode=qv[1]
  27. v=qv[2]
  28. s=cox.hazard(x,v)
  29. s1<-base::summary(s)
  30. #calculate hazard ratio per std(m), given unit (u) or unit change (
  31. #take std
  32. if (mode=='m'){
  33. x.dx<-stats::sd(x[,v],na.rm=TRUE)
  34. }
  35. #use whatever follows u
  36. if (base::substr(mode,1,1)=='u'){
  37. x.dx=base::as.numeric(base::substring(mode,2))
  38. }
  39. #take unit change
  40. if (mode=='logic'){
  41. x.dx=1
  42. }
  43. if (substr(mode,1,1)=='r'){
  44. x.dx=1
  45. }
  46. #adjust output data
  47. sd=base::sqrt(s$var)*x.dx
  48. c=s1$coef[1]*x.dx
  49. l95=base::round(base::exp(c-1.96*sd),2)
  50. u95=base::round(base::exp(c+1.96*sd),2)
  51. HR=base::round(base::exp(c),2)
  52. pWald=base::round(s1$coefficients[1,5],2)
  53. pLikelihood=base::round(s1$logtest['pvalue'],3)
  54. unitChange=base::round(x.dx,2)
  55. #return as data frame with a single row
  56. base::data.frame(varName=v,unitChange=unitChange,
  57. HR=HR,low95=l95,up95=u95,pWald=pWald,pLikelihood=pLikelihood)
  58. }