Assuming the following list:
mylist <- list(a = 1,
b = list(a = "x",
b = "a"))
I now want to replace all occurences of "a" by a certain other description, e.g. "new". Note, the replacement needs to happen for the name of the list elements as well as for the values of list elements.
The expected output would be:
mylist <- list(new = 1,
b = list(new = "x",
b = "new"))
I thought about using rrapply, melt everything into a data frame structure and then go through each column to replace the occurence of "a", but it doesn't work nicely with the generated value column (which has list elements itself).
Any lightweight idea?
Please note: the list depth of my real-life example is much deeper, so I'm looking for an approach that is flexible to handle dynamic list depths.
CodePudding user response:
Using a custom recursive function you could do:
Note: I added a third element containing a list of depth 3 to make the example more general.
mylist <- list(a = 1,
b = list(a = "x",
b = "a"),
c = list(a = "x",
b = list(a = "x",
b = "a")))
rename_element <- function(x) {
if (is.list(x)) {
x <- lapply(x, rename_element)
names(x)[names(x) == "a"] <- "new"
} else {
if (is.character(x)) x[x == "a"] <- "new"
}
return(x)
}
rename_element(mylist)
#> $new
#> [1] 1
#>
#> $b
#> $b$new
#> [1] "x"
#>
#> $b$b
#> [1] "new"
#>
#>
#> $c
#> $c$new
#> [1] "x"
#>
#> $c$b
#> $c$b$new
#> [1] "x"
#>
#> $c$b$b
#> [1] "new"
