Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将结果作为向量(r)存储在for循环中_R_Loops_For Loop - Fatal编程技术网

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

将结果作为向量(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 = "

我有以下输出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 = "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)