How to fill a list with a recursive function in R? -
i'm working hac (hierarchical agglomerative clustering). i've dendrogram, , i'm trying save elements file, make posterior analisys (assign codes elements clusters).
i have recursive function takes branch of dendrogram , returns single list of elements.
my problem following, when function returns list, contains 1 of elements of branch, despite appends each element. here code:
lista_interna<-function(lista,elementos){ print(paste("tam el. ",length(elementos),"")) (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 print here list, contains elements return (elementos) }
where:
- lista: dendrogram branch
- elementos: resulting list (contains elements of supplied branch)
if invoke function, result list 1 element (the first leaf):
empty<-list() res<-lista_interna(dendrogram_branch,empty)
any suggestion welcome.
best regards,
vladimir.
your functions assumes r using call-by-reference semantics wrong. when pass list function , modify it, original list not changed.
what need use return value of recall , concatenate results 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
Comments
Post a Comment