Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge lists in R with partially different keys?

Tags:

merge

list

r

This should be very easy but all examples I found had slightly different objectives.

I got the lists:

lst1 = list(
  Plot      = TRUE,  
  Constrain = c(1:10),
  Box       = "plot" 
)

lst2 = list(
  Plot      = FALSE,
  Lib       = "custom"
)

which store default parameters (lst1) and customized ones (lst2) that should overwrite the defaults. I want as a result:

>lst
  $Plot
  [1] FALSE

  $Constrain
  [1]  1  2  3  4  5  6  7  8  9 10

  $Box
  [1] "plot"

  $Lib
  [1] "custom"

So:

  • parameters of lst2 that do exist in lst1 will overwrite the values
  • parameters of lst1 that do not exist in lst2 will be preserved
  • parameters of lst2 that do not exist in lst1 will be added

I am sorry, I can't figure it out. I tried merge(), though:

lst=merge(lst2,lst1)

gives

[1] Plot      Lib       Constrain Box      
<0 Zeilen> (oder row.names mit Länge 0)

-- EDIT -- The suggested solution by fabians is exactly what I needed. Even more: it handles nested lists, e.g.

ParametersDefault = list(  
  Plot      = list(
    Surface = TRUE,
    PlanView= TRUE
  ),  
  Constrain = c(1:10),
  Box       = "plot" 
)

Parameters = list(
  Plot      = list(
    Surface = FALSE,
    Env     = TRUE
  ),
  Lib       = "custom"
)
Parameters = modifyList(ParametersDefault,Parameters)

print(Parameters$Plot$Surface)
# [1] FALSE

Thanks so much!

like image 599
agoldev Avatar asked Mar 27 '14 13:03

agoldev


2 Answers

lst1 = list(
    Plot      = TRUE,  
    Constrain = c(1:10),
    Box       = "plot" 
)

lst2 = list(
    Plot      = FALSE,
    Lib       = "custom"
)

modifyList(lst1, lst2)
# $Plot
# [1] FALSE
# 
# $Constrain
# [1]  1  2  3  4  5  6  7  8  9 10
# 
# $Box
# [1] "plot"
# 
# $Lib
# [1] "custom"
like image 61
fabians Avatar answered Oct 14 '22 00:10

fabians


You can try:

> c(lst2, lst1[setdiff(names(lst1), names(lst2))])
$Plot
[1] FALSE

$Lib
[1] "custom"

$Constrain
 [1]  1  2  3  4  5  6  7  8  9 10

$Box
[1] "plot"
like image 33
BrodieG Avatar answered Oct 14 '22 00:10

BrodieG