简体   繁体   English

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

[英]How to merge lists in R with partially different keys?

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. 它存储应该覆盖默认值的默认参数(lst1)和自定义参数(lst2)。 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 lst1中存在的lst2参数将覆盖这些值
  • parameters of lst1 that do not exist in lst2 will be preserved lst2中不存在的lst1参数将被保留
  • parameters of lst2 that do not exist in lst1 will be added 将添加lst1中不存在的lst2参数

I am sorry, I can't figure it out. 对不起,我无法弄清楚。 I tried merge(), though: 我试过merge(),但是:

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. - 编辑 - fabians建议的解决方案正是我所需要的。 Even more: it handles nested lists, eg 更多:它处理嵌套列表,例如

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! 非常感谢!

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"

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM