Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over all the key value pairs recursively in a R list and modify a value? [duplicate]

Tags:

replace

list

r

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?

like image 594
Devaraj Phukan Avatar asked Jan 27 '23 07:01

Devaraj Phukan


1 Answers

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
like image 165
markus Avatar answered Jan 29 '23 21:01

markus