方括号[]和双括号[[]]之间的区别是用于访问列表或数据框的元素 [英] The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe
问题描述
R提供了两种不同的方法来访问列表或data.frame的元素-[]
和[[]]
运算符.
两者之间有什么区别?在什么情况下我应该使用另一种?
R语言定义可轻松回答以下类型的问题:
R具有三个基本的索引运算符,其语法由以下示例显示
对于向量和矩阵,虽然
[[
形式与[
形式在语义上有细微差别,但很少使用[[
形式(例如,它删除了任何name或dimnames属性,并且部分匹配用于字符索引).用单个索引对多维结构进行索引时,x[[i]]
或x[i]
将返回x
的第i
个顺序元素.对于列表,通常使用
[[
选择任何单个元素,而[
返回所选元素的列表.
[[
形式仅允许使用整数或字符索引选择单个元素,而[
允许按向量进行索引.请注意,尽管对于列表,索引可以是一个向量,并且向量的每个元素依次应用于列表,所选组件,该组件的所选组件,依此类推.结果仍然是单个元素.
R provides two different methods for accessing the elements of a list or data.frame- the []
and [[]]
operators.
What is the difference between the two? In what situations should I use one over the other?
The R Language Definition is handy for answering these types of questions:
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]]
orx[i]
will return thei
th sequential element ofx
.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.
这篇关于方括号[]和双括号[[]]之间的区别是用于访问列表或数据框的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!