An R Introduction to Statistics

Named List Members

We can assign names to list members, and reference them by names instead of numeric indexes.

For example, in the following, v is a list of two members, named "bob" and "john".

> v = list(bob=c(2, 3, 5), john=c("aa", "bb")) 
> v 
$bob 
[1] 2 3 5 
 
$john 
[1] "aa" "bb"

List Slicing

We retrieve a list slice with the single square bracket "[]" operator. Here is a list slice containing a member of v named "bob".

> v["bob"] 
$bob 
[1] 2 3 5

With an index vector, we can retrieve a slice with multiple members. Here is a list slice with both members of v. Notice how they are reversed from their original positions in v.

> v[c("john", "bob")] 
$john 
[1] "aa" "bb" 
 
$bob 
[1] 2 3 5

Member Reference

In order to reference a list member directly, we have to use the double square bracket "[[]]" operator. The following references a member of v by name.

> v[["bob"]] 
[1] 2 3 5

A named list member can also be referenced directly with the "$" operator in lieu of the double square bracket operator.

> v$bob 
[1] 2 3 5

Search Path Attachment

We can attach a list to the R search path and access its members without explicitly mentioning the list. It should to be detached for cleanup.

> attach(v) 
> bob 
[1] 2 3 5 
> detach(v)