[R] applying a function recursively

Marc Schwartz marc_schwartz at comcast.net
Wed Jun 11 18:23:27 CEST 2008


on 06/11/2008 10:51 AM Georg Otto wrote:
> Hi,
> 
> I have a question about applying a function recursively through a
> list. Suppose I have a list where the different elements have
> different levels of recursion:
> 
> 
>> test.list<-list("I"=list("A"=c("a", "b", "c"), "B"=c("d", "e", "f"), "C"=c("g", "h", "i")),
> +                 "II"=list("A"=list("a"=c("a", "b", "c"), "b"=c("d", "e", "f"),
> +                             "c"=c("g", "h", "i")),
> +                   "B"=c("d", "e", "f"), "C"=c("g", "h", "i")))
> 
>> test.list
> $I
> $I$A
> [1] "a" "b" "c"
> 
> $I$B
> [1] "d" "e" "f"
> 
> $I$C
> [1] "g" "h" "i"
> 
> 
> $II
> $II$A
> $II$A$a
> [1] "a" "b" "c"
> 
> $II$A$b
> [1] "d" "e" "f"
> 
> $II$A$c
> [1] "g" "h" "i"
> 
> 
> $II$B
> [1] "d" "e" "f"
> 
> $II$C
> [1] "g" "h" "i"
> 
> 
> 
> I would like to apply a function recursively to that list, in a way
> that the function does someting with each vector (eg. rev()) and
> returns a list of modified vectors that has the same structure as the
> input list, in my example:
> 
> 
> $I
> $I$A
> [1] "c" "b" "a"
> 
> $I$B
> [1] "f" "e" "d"
> 
> $I$C
> [1] "i" "h" "g"
> 
> 
> $II
> $II$A
> $II$A$a
> [1] "c" "b" "a"
> 
> $II$A$b
> [1] "f" "e" "d"
> 
> $II$A$c
> [1] "i" "h" "g"
> 
> 
> $II$B
> [1] "f" "e" "d"
> 
> $II$C
> [1] "i" "h" "g"
> 
> 
> 
> I understand that with a fixed number of recursion levels one can use
> lapply() in a nested way, but what if the numbers of recursion levels
> is not fixed or is different between the list elements as it is in my
> example?
> 
> Any hint will be appreciated.
> 
> Best,
> 
> Georg

See ?rapply, which is a recursive version of lapply():

 > rapply(test.list, rev, how = "list")
$I
$I$A
[1] "c" "b" "a"

$I$B
[1] "f" "e" "d"

$I$C
[1] "i" "h" "g"


$II
$II$A
$II$A$a
[1] "c" "b" "a"

$II$A$b
[1] "f" "e" "d"

$II$A$c
[1] "i" "h" "g"


$II$B
[1] "f" "e" "d"

$II$C
[1] "i" "h" "g"


HTH,

Marc Schwartz



More information about the R-help mailing list