01 Jan

More R Seeing Objects

This page has the following sections:

Listing objects
Numbers in square brackets
Keep it simple
May not be simple

Listing objects

The command:

> ls()

lists all of the objects in the global environment.

> ls(2)

lists all of the objects that are in whatever is second on the search list.

The command:

> ls(pattern="xx")

lists all of the objects in the global environment with names that have two (lowercase) x’s next to each other.

> ls(pattern="^xx")

lists all of the objects in the global environment with names that begin with two x’s next to each other.

> ls(2, pattern="^xx")

lists all of the objects in the second position on the search list with names that begin with two x’s next to each other.

To let you know about one of my bad habits, I would do the last command as:

> ls(2, pat="^xx")

You can generally abbreviate argument names.

Numbers in square brackets

Sometimes when you print an object each line of the output starts with a number inside square brackets. This happens when you are printing a vector that doesn’t have names. This is R telling you the index for the first item on that line.

Keep it simple

It is quite common that you want to look at an object that you’ve just created, but it is too large to conveniently print it all.

A solution to this is to do:

> head(x)

This will print the first few elements of an atomic vector, the first few components of a list, or the first few rows of a matrix or data frame.

Likewise, you can do:

> tail(x)

to see the last few items.

If you work with large matrices or data frames, then the corner function in the BurStMisc package can be useful.

May not be simple

The print function is generic (see Magic functions, magic objects ), which means that in the case of an object that has a class with a print method what you see is Not what you get.

Kingsford Jones wrote on R-help regarding coming up to speed with R:

I think the real ‘a-ha’ moments came by interactively exploring objects within R. This was vastly facilitated by the use of str and indexing tools.

He goes on to suggest:

Kingsford’s Mantra: “In R we work with objects, and str reveals their essence”

The str function shows an outline of the structure of its argument. For example:

> str(mydf)

might tell you that mydf is a data frame with 2000 observations on 25 variables. It will then tell you the type of each of those 25 variables.

Back to top level of Impatient R

© Copyright - Burns Statistics