Accessing elements ([], [[]], $) in R Programming - Time & Space Complexity
We want to see how fast we can get parts of data from lists or data frames in R.
How does the time to access elements change when the data grows bigger?
Analyze the time complexity of the following code snippet.
my_list <- list(a = 1:1000, b = letters, c = rnorm(1000))
# Access with [] returns a sublist
sublist <- my_list["a"]
# Access with [[]] returns the element itself
element <- my_list[["a"]]
# Access with $ returns the element by name
element2 <- my_list$a
This code shows three ways to get parts of a list: by name with [], [[]], and $.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching the list for the named element.
- How many times: Once per access, no loops inside these operations.
Finding an element by name takes a little longer if the list is bigger, but only a bit.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The time grows roughly in direct proportion to the number of elements.
Time Complexity: O(n)
This means the time to find an element grows linearly with the size of the list.
[X] Wrong: "Accessing elements with $ or [[]] is instant no matter how big the list is."
[OK] Correct: The computer must check names one by one until it finds the right one, so bigger lists take more time.
Knowing how element access time grows helps you write faster R code and shows you understand how data structures work behind the scenes.
"What if the list was replaced by a named vector? How would the time complexity of accessing elements change?"