Ali
Ali

Reputation: 1080

Loop to simulate hierarchical clustering R

I've used the Vectorize function to create a loop for a Kolmogorov Smirnov test for a 50x50 data set and made it output the p-values in a 50x50 matrix. And then stored these p-values as a distance object. Apply hierarchical clustering and store it as a dendrogram object. I repeat this again and then find the cophenetic correlation between them. The code below outputs a 2x2 matrix.

mat1 <- outer(1:50, 1:50, Vectorize(function(i,j)
          {ks.boot(as.numeric(rep(seq(0,14,1),as.vector(data[i,]))),
                   as.numeric(rep(seq(0,14,1),as.vector(data[j,]))),nboots=100)                   
                   $ks.boot.pvalue}))
rownames(mat) <- data2[, 1]
d1=as.dist(as.matrix(1-mat))
hcr1 <- hclust(d,method = "complete")
dend1 <- as.dendrogram(hcr)

mat2 <- outer(1:50, 1:50, Vectorize(function(i,j)
          {ks.boot(as.numeric(rep(seq(0,14,1),as.vector(data[i,]))),
                   as.numeric(rep(seq(0,14,1),as.vector(data[j,]))),nboots=100)                   
                   $ks.boot.pvalue}))
rownames(mat) <- data2[, 1]
d2=as.dist(as.matrix(1-mat))
hcr2 <- hclust(d,method = "complete")
dend2 <- as.dendrogram(hcr)

dendy <- dendlist(dend1,dend2)
cor <- cor.dendlist(dendy1)
cor1

So what I'm after is a for loop to simulate to obtain dend1,dend2,....,dend100. Store this into

dendy <- dendlist(dend1,dend2,...,dend100)

Upvotes: 0

Views: 263

Answers (1)

LAP
LAP

Reputation: 6685

If you only want a list with 100 dend, wrap the relevant code in a custom function without arguments, then lapply it 100 times:

FOO <- function(...){
  mat1 <- outer(1:50, 1:50, Vectorize(function(i,j)
  {ks.boot(as.numeric(rep(seq(0,14,1),as.vector(data[i,]))),
           as.numeric(rep(seq(0,14,1),as.vector(data[j,]))),nboots=100)                   
    $ks.boot.pvalue}))
  rownames(mat) <- data2[, 1]
  d1=as.dist(as.matrix(1-mat))
  hcr <- hclust(d,method = "complete")
  as.dendrogram(hcr)
}

dendy <- lapply(1:100, FOO)

Upvotes: 1

Related Questions