ソースを参照

Adding (classical where graphics is concerned) Kaplan-Meier, updating roc.R to specify ggplo2 as namespace for element_text

Andrej 3 週間 前
コミット
7e2f222fad
4 ファイル変更42 行追加6 行削除
  1. 3 1
      DESCRIPTION
  2. 1 0
      NAMESPACE
  3. 33 0
      R/km.R
  4. 5 5
      R/roc.R

+ 3 - 1
DESCRIPTION

@@ -12,6 +12,8 @@ Roxygen: list(markdown = TRUE)
 RoxygenNote: 7.3.2
 Imports: 
     base,
-    graphics
+    graphics,
+    survival,
+    stats
 Suggests: 
     ggplot2

+ 1 - 0
NAMESPACE

@@ -1,5 +1,6 @@
 # Generated by roxygen2: do not edit by hand
 
+export(kaplan.meier)
 export(mapNA)
 export(remapVariable)
 export(selectValid)

+ 33 - 0
R/km.R

@@ -0,0 +1,33 @@
+#' Create a KM plot
+#'
+#' @param x a data frame that contains followup and censored columns
+#' @param var a categorical variable to split the data to sub-curves
+#' @param comment An additional piece of text to write in the curve
+#'
+#' @return p probability that curves split by var differ significantly
+#'
+#' @export
+
+kaplan.meier<-function(x,var,comment=''){
+	#x should have followup and censored columns	
+	surv.obj<-survival::Surv(x$followup,x$censored)
+    m=base::max(x$followup)
+
+	f<-stats::as.formula(paste('surv.obj',var,sep='~'))
+	s1<-survival::survfit(f,data=x)
+	#str(s1)
+    tit=base::sprintf('Kaplan-Meier plot by %s',var)
+    cols=base::c('red','blue')
+    labels=base::c(base::sprintf('%s=true',var),base::sprintf('%s=false',var))
+	#plot(s1,mark.time=TRUE,col=c('red','blue'),pch=labels,main=tit)
+	graphics::plot(s1,mark.time=TRUE,col=c('red','blue'),main=tit)
+	s=survival::survdiff(f,data=x)
+    #str(s)
+    p=stats::pchisq(s$chisq, length(s$n)-1, lower.tail = FALSE)
+	 sv=base::sprintf("p=%.3f",p)
+    nLab=base::sprintf('N=%d',nrow(x))
+    graphics::text(x=c(0.9*m,0.3*m,0.9*m),y=c(0.2,0.1,0.3),label=c(sv,comment,nLab),cex=1.2)
+    lLab <- base::gsub("x=","",base::names(s1$strata))  ## legend labels
+    graphics::legend("top",legend=lLab,col=cols,lty=c(1,1),horiz=FALSE, bty='n')
+    p
+}

+ 5 - 5
R/roc.R

@@ -295,9 +295,9 @@ simple.plotROCgg<-function(df,vars,cols,x=0.7,y=0.3,unit="ml",precise="FALSE",ta
 
 myTheme<-function(){
    ggplot2::theme(
-            axis.text=element_text(size=14),
-            axis.title=element_text(size=16,face="bold"),
-            legend.title=element_text(size=16,face="bold"),
-            legend.text=element_text(size=12),
-            plot.title=element_text(size=16,face="bold",hjust=0.5))
+            axis.text=ggplot2::element_text(size=14),
+            axis.title=ggplot2::element_text(size=16,face="bold"),
+            legend.title=ggplot2::element_text(size=16,face="bold"),
+            legend.text=ggplot2::element_text(size=12),
+            plot.title=ggplot2::element_text(size=16,face="bold",hjust=0.5))
 }