What is the difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe in R?
When you’re working with lists or data frames in R, there’s a subtle but important distinction between the single bracket [ ]
and the double bracket [[ ]]
operators.
Lists
[ ]
: Returns a sub-list. If you extract one element using single brackets, you still get a list back. For example,my_list[1]
yields a list containing the first element as its own sub-list.[[ ]]
: Returns the actual object at that index. For example,my_list[[1]]
yields the first element itself (not wrapped in a list). This is often used when you want direct access to the contents of a list element (e.g., a numeric vector, a string, etc.).
Data Frames
[ ]
: Returns a data frame (or tibble, if you’re using the tidyverse) with the specified columns or rows. For instance,df[1]
gives you a data frame containing just the first column.[[ ]]
: Returns the column vector itself. For example,df[[1]]
produces a vector rather than a data frame. Similarly,df[[ "colname" ]]
provides direct access to the contents of a specific column.
Why It Matters
Single brackets generally preserve the original structure (subset of rows/columns for data frames, sub-list for lists), while double brackets extract the underlying element. Choosing the correct operator avoids confusion—especially if a function expects a vector rather than a list, or vice versa.
Further Learning
If you want to deepen your coding and problem-solving skills in preparation for technical interviews, check out Grokking the Coding Interview: Patterns for Coding Questions or Grokking Data Structures & Algorithms for Coding Interviews. If you’re looking to design large-scale systems, Grokking System Design Fundamentals can help you master complex architectures. You can also get personalized feedback from ex-FAANG engineers through a Coding Mock Interview or System Design Mock Interview. For more tutorials, visit the DesignGurus.io YouTube channel.