sup.G<-function(x,m=10) { k<-m:0 (4/pi)*sum(((-1)^k)/(2*k+1)*exp(-(pi^2)*((2*k+1)^2)/(8*x^2))) } sup.g<-function(x,m=10) { k<-m:0 (pi/x^3)*sum(((-1)^k)*(2*k+1)*exp(-(pi^2)*((2*k+1)^2)/(8*x^2))) } cnorm<-function(z,thresh=3.6,delta=0.6,kk=4){ check<-F if(z<0){ z<-(-1)*z check<-T } if(z1){ for(k in 1:(kk-1)){ term<-(-1)*term*(2*k-1)/z^2 tally<-tally+term } } out<-tally*dnorm(z)/z if(zerror) { yx<-sup.G(x,m=m) dg<-sup.g(x,m=m) delta<-(1-alpha-yx)/dg x<-x+delta interror<-sup.G(x)-(1-alpha) } x } sup.r<-function(alpha, beta, error=1e-8) { u<-sup.inverse(alpha,error=error) y<-1-beta ml<-qnorm(1-alpha/2)+qnorm(1-beta) x<-ml delta<-1 while(delta>error) { yx<-cnorm(u-x)+exp(2*x*u)*cnorm(u+x) dp<-dnorm(u-x)-exp(2*u*x)*dnorm(u+x)+2*u*exp(2*u*x)*cnorm(u+x) delta<-(y-yx)/dp x<-x+delta } (x/ml)^2 } surv.Rtest<-function (time, delta, group, rho=0, gamma=0, logrank=F, error=1.0e-8) { otime <- order(time) time <- time[otime] delta <- delta[otime] n<-length(time) if((rho+gamma)==0){ weight<-rep(1,n) } else{ km.left<-KM.left(time,delta) weight<-km.left^rho*(1-km.left)^gamma } group <- group[otime] - 1 n2 <- sum(group) atrisk2 <- n2 - cumsum(group) + group n1 <- n-n2 atrisk1 <- n1 - cumsum(1 - group) + 1 - group delta1 <- delta * (1 - group) delta2 <- delta * group y1 <- tapply(atrisk1, time, "max") y2 <- tapply(atrisk2, time, "max") d1 <- tapply(delta1, time, "sum") d2 <- tapply(delta2, time, "sum") weight<-tapply(weight,time,"max") w <- (y1 * y2)/(y1 + y2) terms <- (d1/y1 - d2/y2)[w > 0] temp<-y1+y2-1 temp<-ifelse(temp<1,1,temp) cc<-1-(d1+d2-1)/temp vterms <- (cc*(d1 + d2)/(y1 + y2))[w > 0] weight<-weight[w > 0] w <- w[w > 0] terms <- (weight * w * terms)/sqrt(sum(weight^2 * w * vterms)) temp<-c(0,cumsum(terms)) xs<-max(temp) xi<-min(temp) if(abs(xs)>abs(xi)){test<-xs} else{test<-xi} x <- abs(test) m<-ceiling(max(c(1,(x*sqrt(2)/pi)*sqrt(max(c(1,log(1/(pi*error)))))-0.5))) p<-1-sup.G(x,m=m) out <- NULL out$test <- test out$p <- p if(logrank){ x<-temp[length(temp)] out$test.logrank<-x out$p.logrank<-2*cnorm(abs(x)) } out } KM.left<-function(time,delta){ n<-length(time) dtime<-tapply(time,time,"max") ddelta<-tapply(delta,time,"sum") dy<-tapply(rep(1,n),time,"sum") m<-length(dy) y<-rep(n,m)-c(0,cumsum(dy)[1:(m-1)]) km<-1 km.left<-rep(0,m) for(i in 1:m){ km.left[i]<-km km<-km*(1-ddelta[i]/y[i]) } out<-rep(0,n) for(i in 1:n){ out[i]<-min(km.left[dtime==time[i]]) } out }