Israel
Israel

Reputation: 380

How to calculate standard deviation from columns of list matrix

I got a list of elements called bcvCindex$BootstrapCrossValCindexMat using the following code:

library(prodlim)
set.seed(13)
dat <- SimSurv(100)
library(survival)
library(randomForestSRC)
cox12 <- coxph(Surv(time,status)~X1+X2,data=dat,x=TRUE,y=TRUE)
cox1 <- coxph(Surv(time,status)~X1,data=dat,x=TRUE,y=TRUE)
cox2 <- coxph(Surv(time,status)~X2,data=dat,x=TRUE,y=TRUE)
rsf1 <- rfsrc(Surv(time,status)~X1+X2,data=dat,ntree=15,forest=TRUE)

bcvCindex <- pec::cindex(list("Cox X1"=cox1,
                          "Cox X2"=cox2,
                          "Cox X1+X2"=cox12,
                          "RSF"=rsf1),
                     formula=Surv(time,status)~X1+X2,
                     data=dat,
                     splitMethod="bootcv",
                     B=5,
                     eval.times=seq(1,15,1),keep.index = T, keep.matrix = T)


bcvCindex$BootstrapCrossValCindexMat

Now, I want a function that gets list bcvCindex$BootstrapCrossValCindexMat as input and compute standard deviation for each colum of all matrices that are part of it and save results in a matrix. So I tried this:

sdlist <- function(dat){
  for (i in 1:4) {
    for (j in i:15) {
      desv <- matrix(nrow = 15,ncol = 4)
      desv[i,j] <- sd(dat[[i]][,j],na.rm = TRUE)

    }

  }
  return(desv)
}

sdlist(bcvCindex$BootstrapCrossValCindexMat)

But I get an error. How can I do?

Upvotes: 0

Views: 100

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389225

You have got your indexing wrong I suppose, also maybe j should go from 1:15?

desv <- matrix(nrow = 15,ncol = 4)
for (i in 1:4) {
   for (j in 1:15) {
    desv[j,i] <- sd(bcvCindex$BootstrapCrossValCindexMat[[i]][,j],na.rm = TRUE)
   }
}

desv
#            [,1]       [,2]       [,3]       [,4]
# [1,] 0.12221703 0.27702617 0.21258140 0.17635813
# [2,] 0.06792337 0.19487364 0.10424801 0.10408433
# [3,] 0.04495142 0.10162221 0.04776731 0.04416194
# [4,] 0.04401065 0.03845927 0.02661981 0.03254349
# [5,] 0.04249740 0.02462305 0.03443833 0.04533295
# [6,] 0.03816007 0.02692455 0.03121927 0.03708299
# [7,] 0.03085838 0.01883299 0.03144583 0.03666845
# [8,] 0.02377988 0.02030952 0.03029617 0.04069027
# [9,] 0.02373149 0.02035156 0.02956866 0.05068533
#[10,] 0.02416888 0.02323705 0.03130279 0.06720171
#[11,] 0.02417066 0.02376682 0.02883293 0.08202715
#[12,] 0.02419084 0.02347690 0.02938568 0.05920891
#[13,] 0.02419084 0.02347690 0.02938568 0.05920891
#[14,] 0.02419084 0.02347690 0.02938568 0.05920891
#[15,] 0.02419084 0.02347690 0.02938568 0.05920891

This also can be done with double sapply loop

sapply(bcvCindex$BootstrapCrossValCindexMat, function(x) 
    sapply(1:ncol(x), function(y) sd(x[, y], na.rm = TRUE)))

Upvotes: 1

Related Questions