An R Introduction to Statistics

Data Frame Row Slice

We retrieve rows from a data frame with the single square bracket operator, just like what we did with columns. However, in additional to an index vector of row positions, we append an extra comma character. This is important, as the extra comma signals a wildcard match for the second coordinate for column positions.

Numeric Indexing

For example, the following retrieves a row record of the built-in data set mtcars. Please notice the extra comma in the square bracket operator, and it is not a typo. It states that the 1974 Camaro Z28 has a gas mileage of 13.3 miles per gallon, and an eight cylinder 245 horse power engine, ..., etc.

> mtcars[24,] 
            mpg cyl disp  hp drat   wt  ... 
Camaro Z28 13.3   8  350 245 3.73 3.84  ...

To retrieve more than one rows, we use a numeric index vector.

> mtcars[c(3, 24),] 
            mpg cyl disp  hp drat   wt  ... 
Datsun 710 22.8   4  108  93 3.85 2.32  ... 
Camaro Z28 13.3   8  350 245 3.73 3.84  ...

Name Indexing

We can retrieve a row by its name.

> mtcars["Camaro Z28",] 
            mpg cyl disp  hp drat   wt  ... 
Camaro Z28 13.3   8  350 245 3.73 3.84  ...

And we can pack the row names in an index vector in order to retrieve multiple rows.

> mtcars[c("Datsun 710", "Camaro Z28"),] 
            mpg cyl disp  hp drat   wt  ... 
Datsun 710 22.8   4  108  93 3.85 2.32  ... 
Camaro Z28 13.3   8  350 245 3.73 3.84  ...

Logical Indexing

Lastly, we can retrieve rows with a logical index vector. In the following vector L, the member value is TRUE if the car has automatic transmission, and FALSE if otherwise.

> L = mtcars$am == 0 
> L 
 [1]   FALSE FALSE FALSE  TRUE ...

Here is the list of vehicles with automatic transmission.

> mtcars[L,] 
                     mpg cyl  disp  hp drat    wt  ... 
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215  ... 
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440  ... 
                 ............

And here is the gas mileage data for automatic transmission.

> mtcars[L,]$mpg 
 [1] 21.4 18.7 18.1 14.3 24.4 ...