General List Operations

Now that you’ve seen a simple example of creating a list, let’s look at how to access and work with lists.

List Indexing

You can access a list component in several different ways:

> j$salary
[1] 55000
> j[["salary"]]
[1] 55000
> j[[2]]
[1] 55000

We can refer to list components by their numerical indices, treating the list as a vector. However, note that in this case, we use double brackets instead of single ones.

So, there are three ways to access an individual component c of a list lst and return it in the data type of c:

  • lst$c

  • lst[["c"]]

  • lst[[i]], where i is the index of c within lst

Each of these is useful in different contexts, as you will see in subsequent examples. But note the qualifying phrase, “return it in the data ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.