R提供了两种不同的方法来访问list或data.frame中的元素:[]和[[]]。
这两者之间的区别是什么,什么时候我应该使用其中一个而不是另一个?
R提供了两种不同的方法来访问list或data.frame中的元素:[]和[[]]。
这两者之间的区别是什么,什么时候我应该使用其中一个而不是另一个?
当前回答
哈德利·维克汉姆:
我(蹩脚的外观)修改显示使用tidyverse / purrr:
其他回答
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.
对于另一个具体的用例,当您想要选择split()函数创建的数据帧时,使用双括号。如果您不知道,split()会根据关键字段将列表/数据帧分组为子集。如果你想对多个组进行操作,绘制它们,等等,这很有用。
> class(data)
[1] "data.frame"
> dsplit<-split(data, data$id)
> class(dsplit)
[1] "list"
> class(dsplit['ID-1'])
[1] "list"
> class(dsplit[['ID-1']])
[1] "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
双括号访问列表元素,而单括号返回一个包含单个元素的列表。
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"