R提供了两种不同的方法来访问list或data.frame中的元素:[]和[[]]。

这两者之间的区别是什么,什么时候我应该使用其中一个而不是另一个?


当前回答

为了帮助新手在手动迷雾中导航,看看[[…]]]符号作为一个折叠函数-换句话说,当你只是想从一个命名向量,列表或数据帧中“获取数据”时。如果您想使用来自这些对象的数据进行计算,那么这样做是很好的。这些简单的例子将说明。

(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]

从第三个例子来看

> 2 * x[1]
  x
1 2
> 2 * x[[1]]
[1] 2

其他回答

R语言定义对于回答这些类型的问题很方便:

http://cran.r-project.org/doc/manuals/R-lang.html#Indexing

R has three basic indexing operators, with syntax displayed by the following examples x[i] x[i, j] x[[i]] x[[i, j]] x$a x$"a" For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x. For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements. The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

哈德利·维克汉姆:

我(蹩脚的外观)修改显示使用tidyverse / purrr:

双括号访问列表元素,而单括号返回一个包含单个元素的列表。

lst <- list('one','two','three')

a <- lst[1]
class(a)
## returns "list"

a <- lst[[1]]
class(a)
## returns "character"

[]提取列表,[[]]提取列表中的元素

alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))

str(alist[[1]])
 chr [1:3] "a" "b" "c"

str(alist[1])
List of 1
 $ : chr [1:3] "a" "b" "c"

str(alist[[1]][1])
 chr "a"

作为术语,[[操作符从列表中提取元素,而[操作符获取列表的子集。