Here, we show how to subset or filter a column (or vector), dataframe
and matrix in R with the subset()
and which()
functions.
All the functions are from the "base" package.
See also deleting or naming columns and rows.
Function | Usage |
subset() |
Subset or filter data objects |
which() |
Subset or filter data objects |
Using the columns or vectors below:
[1] 2 4 6 8 10 12 14 16 18 20
[1] "ht" "tt" "ht" "th" "hh"
Select column elements by index number:
[1] 10
[1] 6 8 10 12
[1] "ht" "hh"
Select columns by quality:
Select values greater than 11:
[1] 6 7 8 9 10
[1] 12 14 16 18 20
Select values equal to 12 or “ht”:
[1] 6
[1] 12
[1] 1 3
[1] "ht" "ht"
Using the dataframe below:
dtf = data.frame(Name = c("Randy", "Sam", "Jay", "Reah"),
Team = c("A", "B", "B", "C"),
Hand = c("Right", "Left", "Right", "Right"),
Points = c(8, 9, 7, 9),
Position = c(3, 1, 4, 1))
dtf
Name Team Hand Points Position
1 Randy A Right 8 3
2 Sam B Left 9 1
3 Jay B Right 7 4
4 Reah C Right 9 1
Select first few rows:
Name Team Hand Points Position
1 Randy A Right 8 3
2 Sam B Left 9 1
Select last few rows:
Name Team Hand Points Position
2 Sam B Left 9 1
3 Jay B Right 7 4
4 Reah C Right 9 1
Select a column by name:
Position
1 3
2 1
3 4
4 1
Or alternatively subset the dataframe column as a vector:
Applies to dataframes only.
[1] 3 1 4 1
Select some rows or columns by number:
[1] 8 9 7 9
Name Team Hand Points Position
2 Sam B Left 9 1
3 Jay B Right 7 4
4 Reah C Right 9 1
Select some columns by names, and some rows that are greater than a value:
Applies to dataframes only.
Name Points
1 Randy 8
2 Sam 9
4 Reah 9
Or alternatively, select columns by column numbers c(1, 4), and rows by dtf$Points >= 8:
Applies to dataframes only.
Name Points
1 Randy 8
2 Sam 9
4 Reah 9
Exclude some columns by names, and select some rows that are equal to a value:
Applies to dataframes only.
Name Hand Position
1 Randy Right 3
3 Jay Right 4
4 Reah Right 1
Or alternatively, exclude columns by column numbers c(2, 4), and select rows by dtf$Hand == “Right”:
Applies to dataframes only.
Name Hand Position
1 Randy Right 3
3 Jay Right 4
4 Reah Right 1
Filter by two or more columns:
Name Team Hand Points Position
1 Randy A Right 8 3
4 Reah C Right 9 1
Or alternatively:
Name Team Hand Points Position
1 Randy A Right 8 3
4 Reah C Right 9 1
Select a continuous set of columns by names:
Team Hand Points
1 A Right 8
2 B Left 9
3 B Right 7
4 C Right 9
Or alternatively, select the columns by column numbers (2:4):
Team Hand Points
1 A Right 8
2 B Left 9
3 B Right 7
4 C Right 9
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes