Ali
Ali

Reputation: 1080

Storing results in a for loop as a vector (r)

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 

Upvotes: 0

Views: 569

Answers (1)

markus
markus

Reputation: 26373

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)

Upvotes: 1

Related Questions