An R Introduction to Statistics

Data Frame Column Slice

We retrieve a data frame column slice with the single square bracket "[]" operator.

Numeric Indexing

The following is a slice containing the first column of the built-in data set mtcars.

> mtcars[1] 
                   mpg 
Mazda RX4         21.0 
Mazda RX4 Wag     21.0 
Datsun 710        22.8 
                   ............

Name Indexing

We can retrieve the same column slice by its name.

> mtcars["mpg"] 
                   mpg 
Mazda RX4         21.0 
Mazda RX4 Wag     21.0 
Datsun 710        22.8 
                   ............

To retrieve a data frame slice with the two columns mpg and hp, we pack the column names in an index vector inside the single square bracket operator.

> mtcars[c("mpg", "hp")] 
                   mpg  hp 
Mazda RX4         21.0 110 
Mazda RX4 Wag     21.0 110 
Datsun 710        22.8  93 
                   ............