How can I partially update or merge a list in R?

Here is a list of R:

list1 <- list(var1=1,var2=list(var21=1,var22=2,var23=list(var231=1,var232=0))) 

Here is another list of R:

 list2 <- list(var1=3,var2=list(var22=0,var23=list(var232=1,var233=2)),var3=list(var31=1)) 

Now I want to update list1 to list2 , which should include updating existing values ​​and introducing new values. As a result, var1 , var22 , var232 should be updated to the value specified in list2 , and var233 , var3 , var31 should be entered as new entries. Therefore, the updated list should look like this:

 list(var1=3,var2=list(var21=1,var22=0,var23=list(var231=1,var232=2,var233=2)),var3=list(var31=1)) 

It is very similar to the default settings and user settings. The default settings must be loaded and updated using custom settings. In my use, I simply create the R list from the JSON file ( default.json ) as the default parameters and want to update the default settings with another list created by another JSON file ( user.json ), as many programs do.

Is there an existing package or some simple / decent way to do this?

+6
source share
2 answers

There modifyList for these purposes. Please note that I adjusted the definition of list3 , there is an error in your desired output.

 list4 <- modifyList(list1, list2) list3 <- list(var1=3,var2=list(var21=1,var22=0,var23=list(var231=1,var232=1,var233=2)),var3=list(var31=1)) all.equal(list3, list4) [1] TRUE 
+9
source

Like this:

 Rgames> list1 <- list(var1=1,var2=list(var21=1,var22=2,var23=list(var231=1,var232=0))) Rgames> list2 <- list(var1=3,var2=list(var22=0,var23=list(var232=1,var233=2)),var3=list(var31=1)) Rgames> matchname<-intersect(names(list1),names(list2)) Rgames> diffname<-setdiff(names(list2),names(list1)) Rgames> for (j in c(matchname,diffname)) list1[[j]]<-list2[[j]] Rgames> list1 $var1 [1] 3 $var2 $var2$var22 [1] 0 $var2$var23 $var2$var23$var232 [1] 1 $var2$var23$var233 [1] 2 $var3 $var3$var31 [1] 1 

intersect finds all the elements in both sets, so I can replace them in list1 . setdiff finds items in list2 , not list1 , so I can add them. In fact, you could just do for(j in names(list2)) list1[[j]] <- list2[j]] , but I expanded it to show how you can do a slightly different merge.

0
source

All Articles