为什么在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?

查看:116
本文介绍了为什么在R中用list [n]而不是list [[n]]索引到列表中,却不能达到您的期望?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R列表中,为什么用[n]而不是[[n]]进行索引时不会像非R程序员所期望的那样返回第n个元素?

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

推荐答案

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

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

来自 R入门手册:6.1列表 :

将Lst [[1]]与Lst [1] 区分开来非常重要.

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

"[[…]]"是用于选择单个元素的运算符,

"[…]"是一般的下标运算符.

因此,前者是列表Lst中的第一个对象,如果它是命名列表,则不包括名称.后者是列表Lst的子列表,仅由第一个条目组成.如果它是一个命名列表,则名称将转移到子列表中.

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用户一如既往地坚持说,它确实按照它说的去做(在某些地方是深层的且未编制索引). doc.但是, 的帮助页面list 仅显示您如何创建列表,但不显示如何对其进行索引(!).仅

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(!)

这篇关于为什么在R中用list [n]而不是list [[n]]索引到列表中,却不能达到您的期望?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆