[R] Break during the recursion?

hadley wickham h.wickham at gmail.com
Sun Jul 15 22:04:12 CEST 2007


On 7/15/07, Atte Tenkanen <attenka at utu.fi> wrote:
> Here is now more elegant function for inorder tree walk, but I still can't save the indexes!? This version now prints them ok, but if I use return, I get only the first v[i].
>
> leftchild<-function(i){return(2*i)}
>
> rightchild<-function(i){return(2*i+1)}
>
> iotw<-function(v,i)
>
> {
>         if (is.na(v[i])==FALSE & is.null(unlist(v[i]))==FALSE)
>         {
>                 iotw(v,leftchild(i))
>                 print(v[i]) # return doesn't work here
>                 iotw(v,rightchild(i))
>         }
> }

Shouldn't you return:

c(iotw(v, leftchild(i)), v[i], iotw(v, rightchild(i)))

(and rewrite the conditition to return null if the node doesn't exist,
I think it reads clearer that way)

Hadley



More information about the R-help mailing list