[英]Storing results in a for loop as a vector (r)
I have the following function which outputs 100 objects. 我有以下输出100个对象的函数。 I've tried to get it to output as a vector with no luck due to my limited understanding of R. 由于对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
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. 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.