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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.