Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

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?

like image 748
Sharpie Avatar asked Jul 23 '09 03:07

Sharpie


People also ask

What does double brackets mean in Python?

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.

What do double brackets mean in pandas?

The single bracket will output a Pandas Series, while a double bracket will output a Pandas DataFrame.

What do double square brackets do in R?

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.

What is the difference between brackets and parentheses in R?

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.)


1 Answers

The R Language Definition is handy for answering these types of questions:

  • 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.

like image 138
ars Avatar answered Oct 05 '22 10:10

ars