0

I have the following function which outputs 100 objects. I've tried to get it to output as a vector with no luck due to my limited understanding of R.

corr <- function(...){
for (i in 1:100){
  a <- as.vector(cor_cophenetic(dend03$dend[[i]],dend01$dend[[2]]))
  print(a)
}
}
corr(a)

Which command outputs this as a vector? Currently the output looks like

[1] 0.9232859
[1] 0.9373974
[1] 0.9142569
[1] 0.8370845
:
:
[1] 0.9937693

Sample data:

> dend03
$hcr
$hcr[[1]]

Call:
hclust(d = d, method = "complete")

Cluster method   : complete 
Number of objects: 30 

$dend
$dend[[1]]
'dendrogram' with 2 branches and 30 members total, at height 1 

$dend[[2]]
'dendrogram' with 2 branches and 30 members total, at height 1 
Ali
  • 1,048
  • 8
  • 19
  • Not the best solution is to concat old and new vector. First initialize `a <- c()` then in for loop `a <- c(a, cor_cophen...)` – RobJan Aug 13 '18 at 10:29
  • This outputs a lower triangle matrix, Not sure what its doing. – Ali Aug 13 '18 at 10:35
  • 1
    Could you give a sample data for `dend03` ? – RobJan Aug 13 '18 at 10:36
  • Sample data added. The objects inside are both hierarchical clusterings and dendrogram objects – Ali Aug 13 '18 at 10:57
  • @markus it outputs a vector but only the first cophenetic correlation is outputted. The rest are 0's. – Ali Aug 13 '18 at 10:58
  • 1
    @Ali My bad. Put the part `a <- vector("double", 100)` at the beginning of your function, then `a[[i]] <- as.vector(cor_cophenetic(dend03$dend[[i]], dend01$dend[[2]]))` inside the loop and finally `return(a)` at the end of your function. – markus Aug 13 '18 at 11:01
  • 1
    Please share sample of your data using `dput()` (not `str` or `head` or picture/screenshot) so others can help. See more here https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 – Tung Aug 13 '18 at 11:21
  • @markus thanks a lot! runs perfectly – Ali Aug 13 '18 at 11:49
  • @Tung noted for next time. Thank you. – Ali Aug 13 '18 at 11:49

1 Answers1

1

The problem with OP's code is that the function doesn't return a vector but printed the value at each point of the iteration to the console.

corr <- function(...) {
  a <- vector("double", length = 100) # initialse a vector of type double
  for (i in seq_len(n)) {
    a[[i]] <- cor_cophenetic(dend03$dend[[i]], 
                             dend01$dend[[2]])) # fill in the value at each iteration
  }
  return(a) # return the result
}

corr(a)
markus
  • 25,843
  • 5
  • 39
  • 58