R中双嵌套列表的奇怪行为
Weird behavior of double-nested lists in R
这只花了我两个小时的调试时间来识别:
> list1 = list() # empty list
> list1['first'] = list(a=list(a1='goat', a2='horse'), b=42) # double-nested
> print(list1$first$b)
NULL # Should be 42?
> print(list1) # let's check the actual contents of list1
$first
$first$a1 # how did the contents of the innermost a-list end up here?
[1] "goat"
$first$a2
[1] "horse"
在这种情况下,分配给 'first'
的列表将成为 a
中的列表,因此 b
会在没有警告的情况下消失。这里发生了什么,b
值去了哪里?
我正在使用 R 3.0.2。当 R 阻止我执行上述操作时,我该如何执行此类操作?
正如 joran 在评论中指出的那样,解决方案是在赋值中使用双括号:
list1[['first']] = list(a=list(a1='goat', a2='horse'), b=42)
显然,如果您使用单括号,您会在较新的 R 版本中收到警告,但在旧版本中不会收到警告。
这只花了我两个小时的调试时间来识别:
> list1 = list() # empty list
> list1['first'] = list(a=list(a1='goat', a2='horse'), b=42) # double-nested
> print(list1$first$b)
NULL # Should be 42?
> print(list1) # let's check the actual contents of list1
$first
$first$a1 # how did the contents of the innermost a-list end up here?
[1] "goat"
$first$a2
[1] "horse"
在这种情况下,分配给 'first'
的列表将成为 a
中的列表,因此 b
会在没有警告的情况下消失。这里发生了什么,b
值去了哪里?
我正在使用 R 3.0.2。当 R 阻止我执行上述操作时,我该如何执行此类操作?
正如 joran 在评论中指出的那样,解决方案是在赋值中使用双括号:
list1[['first']] = list(a=list(a1='goat', a2='horse'), b=42)
显然,如果您使用单括号,您会在较新的 R 版本中收到警告,但在旧版本中不会收到警告。