如何将R中的列表与部分不同的键合并?

ago*_*dev 6 merge r list

这应该很容易,但我发现的所有例子都有不同的目标.

我得到了这些清单:

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

lst2 = list(
  Plot      = FALSE,
  Lib       = "custom"
)
Run Code Online (Sandbox Code Playgroud)

它存储应该覆盖默认值的默认参数(lst1)和自定义参数(lst2).我想要的结果是:

>lst
  $Plot
  [1] FALSE

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

  $Box
  [1] "plot"

  $Lib
  [1] "custom"
Run Code Online (Sandbox Code Playgroud)

所以:

  • lst1中存在的lst2参数将覆盖这些值
  • lst2中不存在的lst1参数将被保留
  • 将添加lst1中不存在的lst2参数

对不起,我无法弄清楚.我试过merge(),但是:

lst=merge(lst2,lst1)
Run Code Online (Sandbox Code Playgroud)

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

- 编辑 - fabians建议的解决方案正是我所需要的.更多:它处理嵌套列表,例如

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
Run Code Online (Sandbox Code Playgroud)

非常感谢!

fab*_*ans 12

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"
Run Code Online (Sandbox Code Playgroud)

  • 新的一个给我,+ 1. (2认同)