将结果存储在for循环中作为向量(r)

时间:2018-08-13 10:18:39

标签: r loops for-loop

我具有以下输出100个对象的功能。由于对R的了解有限,我试图将其作为矢量输出,但没有运气。

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

哪个命令将其输出为向量?当前输出看起来像

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

样本数据:

> 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 

1 个答案:

答案 0 :(得分:1)

OP代码的问题是该函数不返回向量,而是在迭代的每个点将值打印到控制台。

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)