将结果作为向量(r)存储在for循环中
我有以下输出100个对象的函数。由于我对R的理解有限,我一直试图将其作为向量输出,但运气不佳将结果作为向量(r)存储在for循环中,r,loops,for-loop,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) 样本数据: > dend03 $hcr $hcr[[1]] Call: hclust(d = d, method = "
corr <- function(...){
for (i in 1:100){
a <- as.vector(cor_cophenetic(dend03$dend[[i]],dend01$dend[[2]]))
print(a)
}
}
corr(a)
样本数据:
> 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)
corr最好的解决方案不是将新旧向量结合起来。首先初始化a这会输出一个较低的三角形矩阵,不知道它在做什么。你能给出dend03
的示例数据吗?@Ali My bad。请使用dput()
(不是str
或head
或图片/屏幕截图)共享您的数据样本,以便其他人可以提供帮助。在这里看到更多
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)