简体   繁体   中英

How to fill a list with a recursive function in R?

I'm working with 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
  • elementos: is the resulting list (contains all the elements of the supplied branch)

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. 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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