Eswar Eswar - 2 months ago 6
R Question

R : Swapping 2 values in a nested list

[[1]]
[[1]][[1]]
[1] 1 46 107 69 1

[[1]][[2]]
[1] 1 146 145 71 92 1
####################
[[2]]
[[2]][[1]]
[1] 1 46 18 92 1

[[2]][[2]]
[1] 1 127 145 53 168 1


Assume I have 2 nested list, as shown above, I'm looking for function where I can update (say 46) in both the list with some other number in list (say 92) and update 92's with 46 without altering the structure of the list

Expected output will be something like this

[[1]]
[[1]][[1]]
[1] 1 92 107 69 1

[[1]][[2]]
[1] 1 146 145 71 46 1
####
[[2]]
[[2]][[1]]
[1] 1 92 18 46 1

[[2]][[2]]
[1] 1 127 145 53 168 1


Rlist library has functions like list.find/list.findi which works only for named nested list. Mine is not a named list

Answer

Could it be a simple rapply? See this example, where 46 is replaced by 92 (and the other way round, as added by @akrun):

li = list(list(c(1, 46, 107, 69, 1),
               c(1, 146, 145, 71, 92, 1)))
# [[1]]
# [[1]][[1]]
# [1]   1  46 107  69   1
# 
# [[1]][[2]]
# [1]   1 146 145  71  92   1

rapply(li, function(x) ifelse(x == 46, 92,ifelse(x==92, 46, x)), how = "list")

# [[1]]
# [[1]][[1]]
# [1]   1  92 107  69   1
# 
# [[1]][[2]]
# [1]   1 146 145  71  46   1

The how = "list" makes sure you get the original structure back.