I want to modify the values of a list recursively based on some condition.
mylist = list(a = "test1",
b = list(bb = "test2", list(bbb = "test1")),
c = "test2")
I would like to modify the value if it is test1 and replace it in this list or create a new list. E.g if the modification was to replace test1 with best1, the resultant list should be
mylist = list(a = "best1",
b = list(bb = "test2", list(bbb = "best1")),
c = "test2")
What is the cleanest way to do this in R?
You can use rapply
out <- rapply(mylist, function(x) replace(x, x == "test1", "best1"), how = "replace")
Check the output
identical(out,
list(a = "best1",
b = list(bb = "test2", list(bbb = "best1")),
c = "test2"))
# [1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With