R provides two different methods for accessing the elements of a list or data.frame: []
and [[]]
.
What is the difference between the two, and when should I use one over the other?
Select a column or columns in a dataframe With one column name, single pair of brackets returns a Series, while double brackets return a dataframe.
The single bracket will output a Pandas Series, while a double bracket will output a Pandas DataFrame.
The single and double square brackets are used as indexing operators in R Programming Language. Both of these operators are used for referencing the components of R storage objects either as a subset belonging to the same data type or as an element.
Parentheses are for functions, brackets are for indicating the position of items in a vector or matrix. (Here, items with numbers like x1 are user-supplied variables.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With