Why does indexing into a list with list[n] instead

2019-09-26 04:34发布

In an R list, why does indexing with [n] instead of [[n]] not return the nth element as non-R-programmers would expect?

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

1条回答
forever°为你锁心
2楼-- · 2019-09-26 04:56

Because in general l[n] returns a sublist (possibly of length one), whereas l[[n]] returns an element:

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

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

From 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.

This is an R gotcha (R being different to other languages in a non-obvious and under-documented way), although as ever some R users will insist it's doing exactly what it says, (somewhere deep and unindexed) in the doc. However, the help-page for list only shows you how to create a list but does not show how to index into it(!) Only ?[ or ?Extract manpages actually tell you how to index into a list(!)

查看更多
登录 后发表回答