簡體   English   中英

將結果存儲在for循環中作為向量(r)

[英]Storing results in a for loop as a vector (r)

我有以下輸出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 

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM