Skip to Content
Course content

95: Working with Nested Lists

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're organizing a physical archive of project files. You don't just throw every single piece of paper into one giant box. Instead, you have a filing cabinet (the main list). Inside that cabinet, you have drawers (the first level of nesting). Inside each drawer, you have manila folders (the second level), and inside those folders, you finally find the actual documents or sticky notes (the values).

In R, a nested list is exactly that: a list where one or more of the elements are themselves lists. It's the primary way we handle hierarchical data—the kind of stuff you'll see constantly when you start working with JSON APIs or complex model outputs from packages like lme4 or caret.

Mapping the Archive to the Code

Let's take that archive analogy and turn it into a real scenario. Suppose we're tracking data for a few software projects. Each project has a name, a lead developer, and a sub-list of current milestones.

projects <- list(
  project_alpha = list(
    lead = "Sarah",
    milestones = list(
      m1 = "API Design",
      m2 = "Database Schema"
    )
  ),
  project_beta = list(
    lead = "Marcus",
    milestones = list(
      m1 = "Frontend Prototype",
      m2 = "User Testing"
    )
  )
)

Here is how the analogy maps:

  • The Cabinet: The projects list itself.
  • The Drawer: projects$project_alpha. This is a list containing everything about Project Alpha.
  • The Folder: projects$project_alpha$milestones. This is another list nested inside the first one.
  • The Document: projects$project_alpha$milestones$m1. This is the final string, "API Design".

Drilling Down with Double Brackets

You've probably used the $ operator, which is great when you know the names of your elements. But in a professional production environment, you'll often be looping through lists where the names are dynamic. That's where double brackets [[ ]] come in.

I'll be honest: the difference between [ ] and [[ ]] is where most R beginners get tripped up. Remember that [ ] returns a slice (a smaller list), while [[ ]] returns the actual content inside that slice.

# This returns a list containing the project_alpha list
slice <- projects[1] 

# This returns the actual list for project_alpha
content <- projects[[1]] 

# To get the first milestone of the first project:
milestone_val <- projects[[1]][[2]][[1]]
# Result: "API Design"

Think of [[ ]] as "reaching inside" the container. To get to that first milestone, we reached into the cabinet [[1]], then into the milestones folder [[2]], and finally grabbed the first single item [[1]].

Surgical Edits to Deeply Buried Data

Updating a nested list is straightforward once you've navigated to the specific "document" you want to change. You just use the assignment operator <- at the end of your navigation path.

Let's say Project Beta just finished its first milestone and moved to "Beta Release". You don't need to redefine the whole list; you just target that one leaf node:

projects$project_beta$milestones$m1 <- "Beta Release"

If you're using indices instead of names, it looks like this:

projects[[2]][[2]][[1]] <- "Beta Release"

One quick tip from experience: when your lists get more than three levels deep, stop and ask yourself if you should be using a data.frame or a tibble. Nested lists are powerful, but if you find yourself writing [[1]][[4]][[2]][[1]], your code becomes a nightmare to debug because it's impossible to tell what those numbers actually represent just by looking at them.




📋 Practical Task

Building a Multi-City Weather Archive

You need to create a nested list structure to store weather observations for three different cities. Each city should be a named element in the main list. Inside each city, create two nested lists: metadata (containing the country and timezone) and readings (containing a list of temperatures for 'Monday', 'Tuesday', and 'Wednesday').

Your requirements:

  • Create the nested list for cities: "London", "Tokyo", and "New York".
  • Assign a temperature value to each day for each city.
  • Update the temperature for Tokyo on Tuesday to a new value using double brackets [[ ]].
  • Extract and print only the timezone for New York using the $ operator.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.