[
, [[
, and $
This topic covers the most common syntax to access specific rows and columns of a data frame. These are
matrix
with single brackets data[rows, columns]
list
:
data[columns]
to get a data framedata[[one_column]]
to get a vector$
for a single column data$column_name
We will use the built-in mtcars
data frame to illustrate.
data[rows, columns]
Using the built in data frame mtcars
, we can extract rows and columns using []
brackets with a comma included. Indices before the comma are rows:
# get the first row
mtcars[1, ]
# get the first five rows
mtcars[1:5, ]
Similarly, after the comma are columns:
# get the first column
mtcars[, 1]
# get the first, third and fifth columns:
mtcars[, c(1, 3, 5)]
As shown above, if either rows or columns are left blank, all will be selected. mtcars[1, ]
indicates the first row with all the columns.
So far, this is identical to how rows and columns of matrices are accessed. With data.frame
s, most of the time it is preferable to use a column name to a column index. This is done by using a character
with the column name instead of numeric
with a column number:
# get the mpg column
mtcars[, "mpg"]
# get the mpg, cyl, and disp columns
mtcars[, c("mpg", "cyl", "disp")]
Though less common, row names can also be used:
mtcars["Mazda Rx4", ]
The row and column arguments can be used together:
# first four rows of the mpg column
mtcars[1:4, "mpg"]
# 2nd and 5th row of the mpg, cyl, and disp columns
mtcars[c(2, 5), c("mpg", "cyl", "disp")]
When using these methods, if you extract multiple columns, you will get a data frame back. However, if you extract a single column, you will get a vector, not a data frame under the default options.
## multiple columns returns a data frame
class(mtcars[, c("mpg", "cyl")])
# [1] "data.frame"
## single column returns a vector
class(mtcars[, "mpg"])
# [1] "numeric"
There are two ways around this. One is to treat the data frame as a list (see below), the other is to add a drop = FALSE
argument. This tells R to not "drop the unused dimensions":
class(mtcars[, "mpg", drop = FALSE])
# [1] "data.frame"
Note that matrices work the same way - by default a single column or row will be a vector, but if you specify drop = FALSE
you can keep it as a one-column or one-row matrix.
Data frames are essentially list
s, i.e., they are a list of column vectors (that all must have the same length). Lists can be subset using single brackets [
for a sub-list, or double brackets [[
for a single element.
data[columns]
When you use single brackets and no commas, you will get column back because data frames are lists of columns.
mtcars["mpg"]
mtcars[c("mpg", "cyl", "disp")]
my_columns <- c("mpg", "cyl", "hp")
mtcars[my_columns]
Single brackets like a list vs. single brackets like a matrix
The difference between data[columns]
and data[, columns]
is that when treating the data.frame
as a list
(no comma in the brackets) the object returned will be a data.frame
. If you use a comma to treat the data.frame
like a matrix
then selecting a single column will return a vector but selecting multiple columns will return a data.frame
.
## When selecting a single column
## like a list will return a data frame
class(mtcars["mpg"])
# [1] "data.frame"
## like a matrix will return a vector
class(mtcars[, "mpg"])
# [1] "numeric"
data[[one_column]]
To extract a single column as a vector when treating your data.frame
as a list
, you can use double brackets [[
. This will only work for a single column at a time.
# extract a single column by name as a vector
mtcars[["mpg"]]
# extract a single column by name as a data frame (as above)
mtcars["mpg"]
$
to access columnsA single column can be extracted using the magical shortcut $
without using a quoted column name:
# get the column "mpg"
mtcars$mpg
Columns accessed by $
will always be vectors, not data frames.
$
for accessing columnsThe $
can be a convenient shortcut, especially if you are working in an environment (such as RStudio) that will auto-complete the column name in this case. However, $
has drawbacks as well: it uses non-standard evaluation to avoid the need for quotes, which means it will not work if your column name is stored in a variable.
my_column <- "mpg"
# the below will not work
mtcars$my_column
# but these will work
mtcars[, my_column] # vector
mtcars[my_column] # one-column data frame
mtcars[[my_column]] # vector
Due to these concerns, $
is best used in interactive R sessions when your column names are constant. For programmatic use, for example in writing a generalizable function that will be used on different data sets with different column names, $
should be avoided.
Also note that the default behaviour is to use partial matching only when extracting from recursive objects (except environments) by $
# give you the values of "mpg" column
# as "mtcars" has only one column having name starting with "m"
mtcars$m
# will give you "NULL"
# as "mtcars" has more than one columns having name starting with "d"
mtcars$d
Whenever we have the option to use numbers for a index, we can also use negative numbers to omit certain indices or a boolean (logical) vector to indicate exactly which items to keep.
mtcars[1, ] # first row
mtcars[ -1, ] # everything but the first row
mtcars[-(1:10), ] # everything except the first 10 rows
We can use a condition such as <
to generate a logical vector, and extract only the rows that meet the condition:
# logical vector indicating TRUE when a row has mpg less than 15
# FALSE when a row has mpg >= 15
test <- mtcars$mpg < 15
# extract these rows from the data frame
mtcars[test, ]
We can also bypass the step of saving the intermediate variable
# extract all columns for rows where the value of cyl is 4.
mtcars[mtcars$cyl == 4, ]
# extract the cyl, mpg, and hp columns where the value of cyl is 4
mtcars[mtcars$cyl == 4, c("cyl", "mpg", "hp")]