为什么在 R 中使用 list[n] 而不是 list[[n]] 索引到列表中并没有达到您的预期?

Why does indexing into a list with list[n] instead of list[[n]] in R not do what you would expect?

在 R 列表中,为什么使用 [n] 而不是 [[n]] 进行索引而不是 return 非 R 程序员所期望的第 n 个元素?

lfile <- list('fileA.xls', 'file2.xls', 'fileY.xls')
ll <- list(list(1,2), list(3), list(4,5,6), list(7,8))
lv <- list(c(1,2), c(3), c(4,5,6), c(7,8))

> lfile[2]
[[1]]
[1] "file2.xls" # returns SUBLIST, not n'th ELEMENT

> lfile[[2]]
[1] "file2.xls" # returns ELEMENT

因为通常 l[n] returns 是一个子列表(可能长度为 1),而 l[[n]] returns 是一个元素 :

> lfile[2]
[[1]]
[1] "file2.xls" # returns SUBLIST of length one, not n'th ELEMENT

> lfile[[2]]
[1] "file2.xls" # returns ELEMENT

来自R intro manual: 6.1 Lists

It is very important to distinguish Lst[[1]] from Lst[1].

‘[[…]]’ is the operator used to select a single element,

whereas ‘[…]’ is a general subscripting operator.

Thus the former is the first object in the list Lst, and if it is a named list the name is not included. The latter is a sublist of the list Lst consisting of the first entry only. If it is a named list, the names are transferred to the sublist.

这是一个 R 陷阱(R 与其他语言的不同之处在于一种不明显且记录不足的方式),尽管一些 R 用户会一如既往地坚持说它完全按照它说的去做,(某个地方很深而且没有索引)在文档中。但是,list only shows you how to create a list but does not show how to index into it(!) Only ?[ or ?Extract 联机帮助页的帮助页面实际上告诉您如何索引到列表 (!)