Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lapply over nested list and retain naming/structure

Tags:

r

When creating nested lists R has, what I consider, helpful naming structure for the elements of the list. I have a list of lists and want to apply a function of every single vector contained within any list. lapply does this but then strips the naming structure of the list. How can I lapply of every vector element of the nested list without stripping the names? I tried passing the index instead but that seems to do the same thing (strip names).

TEST <- list(n1=list(a="5", b="65"), n2=list(a="f", b= "f6"))
TEST
lapply(TEST, function(x) gsub("6", "foo", x))
lapply(seq_along(TEST), function(i) gsub("6", "foo", TEST[[i]]))

Console Output:

> TEST
$n1
$n1$a
[1] "5"

$n1$b
[1] "65"


$n2
$n2$a
[1] "f"

$n2$b
[1] "f6"


> lapply(TEST, function(x) gsub("6", "foo", x))
$n1
[1] "5"    "foo5"

$n2
[1] "f"    "ffoo"

Desired outcome:

$n1
$n1$a
[1] "5"

$n1$b
[1] "foo5"


$n2
$n2$a
[1] "f"

$n2$b
[1] "ffoo"
like image 552
Tyler Rinker Avatar asked Nov 28 '12 15:11

Tyler Rinker


1 Answers

It seems you want the rapply variant of the *apply family

rapply(TEST, function(x){gsub("6", "foo", x)}, how = "list")

$n1
$n1$a
[1] "5"

$n1$b
[1] "foo5"


$n2
$n2$a
[1] "f"

$n2$b
[1] "ffoo"

You could also do it like this to avoid writing an anonymous function

rapply(TEST, gsub, pattern = "6", replacement = "foo", how = "list")
like image 171
Dason Avatar answered Oct 12 '22 23:10

Dason