O'Reilly logo

R in a Nutshell, 2nd Edition by Joseph Adler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Accessing Data Structures

R has some specialized syntax for accessing data structures. You can fetch a single item from a structure, or multiple items (possibly as a multidimensional array) using R’s index notation. You can fetch items by location within a data structure or by name.

Data Structure Operators

Table 6-2 shows the operators in R used for accessing objects in a data structure.

Table 6-2. Data structure access notation

SyntaxObjectsDescription
x[i]Vectors, listsReturns objects from object x, described by i. i may be an integer vector, character vector (of object names), or logical vector. Does not allow partial matches. When used with lists, returns a list. When used with vectors, returns a vector.
x[[i]]Vectors, listsReturns a single element of x, matching i. i may be an integer or character vector of length 1. Allows partial matches (with exact=FALSE option).
x$nListsReturns object with name n from object x.
x@nS4 objectsReturns element stored in object x in slot named n.

Although the single-bracket notation and double-bracket notation look very similar, there are three important differences. First, double brackets always return a single element, while single brackets may return multiple elements. Second, when elements are referred to by name (as opposed to by index), single brackets match only named objects exactly, while double brackets allow partial matches. Finally, when used with lists, the single-bracket notation returns a list, but the double-bracket notation returns ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required