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
df[condition, ]keeps matching rows.df[, cols]keeps named columns; both combine.subsetandorderfilter and sort more readably.
Keywords and builtins used here
cheadnrowordersubset
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.
Step 2 of 3 in Building & inspecting, step 2 of 8 in Data frames in base R.