typestar

Subsetting rows and columns in R

Filtering and selecting with base R brackets.

heavy <- mtcars[mtcars$wt > 3.5, ]
two_cols <- mtcars[, c("mpg", "cyl")]
both <- mtcars[mtcars$cyl == 4, c("mpg", "wt")]

efficient <- subset(mtcars, mpg > 25, select = c(mpg, wt))
ordered <- mtcars[order(-mtcars$mpg), ]
top_five <- head(ordered, 5)

count <- nrow(heavy)

How it works

  1. df[condition, ] keeps matching rows.
  2. df[, cols] keeps named columns; both combine.
  3. subset and order filter and sort more readably.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
271
Tokens
90
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 2 of 3 in Building & inspecting, step 2 of 8 in Data frames in base R.

← Previous Next →