简体   繁体   English

如何用R中的递归函数填充列表?

[英]How to fill a list with a recursive function in R?

I'm working with HAC (Hierarchical Agglomerative Clustering). 我正在使用HAC(Hierarchical Agglomerative Clustering)。 I've a dendrogram, and I'm trying to save the elements to a file, to make posterior analisys (assign codes to elements by clusters). 我有一个树状图,我正在尝试将元素保存到文件中,以进行后验分析(通过聚类为元素分配代码)。

I have a recursive function which takes a branch of dendrogram and returns a single list of elements. 我有一个递归函数,它接受树形图的一个分支并返回一个元素列表。

My problem is the following, when the function returns the list, it only contains one of the elements of my branch, despite that appends properly each element. 我的问题如下,当函数返回列表时,它只包含我的分支的一个元素,尽管每个元素都正确附加。 Here is my code: 这是我的代码:

lista_interna<-function(lista,elementos){
  print(paste("Tam El. ",length(elementos),""))
  for (i in 1:length(lista)){
    if(typeof(lista[[i]])=="integer"){
      print("agrega agrega...")
      elementos[[length(elementos)+1L]]<-lista[[i]]
    }else if(typeof(lista[[i]])=="list"){
      print("Hace Recall....")
      Recall(lista[[i]],elementos);
    }
  }
  print(elementos) # when I print here the list, contains all elements
  return (elementos)
}

Where: 哪里:

  • lista: is the dendrogram branch lista:是树形图分支
  • elementos: is the resulting list (contains all the elements of the supplied branch) elementos:是结果列表(包含所提供分支的所有元素)

If a invoke the function, the result is a list with one element (the first leaf): 如果调用该函数,结果是一个包含一个元素的列表(第一个叶子):

empty<-list()
res<-lista_interna(dendrogram_branch,empty)

Any suggestion will be welcome. 任何建议都将受到欢迎。

Best regards, 最好的祝福,

Vladimir. 弗拉基米尔。

Your functions assumes that R is using call-by-reference semantics which is wrong. 您的函数假定R正在使用错误引用的call-by-reference语义。 When you pass a list into a function and modify it, the original list will not be changed. 将列表传递给函数并进行修改时,原始列表不会更改。

What you need to do is to use the return value of Recall and concatenate the results as is the following example: 您需要做的是使用Recall的返回值并连接结果,如下例所示:

f = function (x) { 
       if (x <=0 ) {
          return( c() )
       } else {
         return( c(Recall(x-1),x) )
       }
    }

# f(5)
# [1] 1 2 3 4 5         

Comment: please post a reproducible example. 评论:请发布一个可重复的例子。

Quick answer: Use: 快速回答:使用:

elementos <- Recall(lista[[i]],elementos)

Have you tried this ? 你试过这个吗?

unlist(lista)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM