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:
它存储应该覆盖默认值的默认参数(lst1)和自定义参数(lst2)。我希望结果如下:
>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
lst1中存在的lst2参数将覆盖这些值
lst2中不存在的lst1参数将被保留
将添加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 f*s is exactly what I needed. Even more: it handles nested lists, e.g.
- 编辑 - f*s建议的解决方案正是我所需要的。更多:它处理嵌套列表,例如
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!
非常感谢!
2 个解决方案
#1
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"
#2
4
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"
#1
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"
#2
4
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"