You can use the following methods to select rows from a data frame by index in R:
Method 1: Select One Row by Index
#select third row
df[3,]
Method 2: Select Multiple Rows by Index
#select third, fourth, and sixth rows
df[c(3, 4, 6),]
Method 3: Select Range of Rows by Index
#select rows 2 through 5
df[2:5,]
The following examples show how to use each method in practice with the following data frame:
#create data frame df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'), points=c(19, 14, 14, 29, 25, 30), assists=c(4, 5, 5, 4, 12, 10), rebounds=c(9, 7, 7, 6, 10, 11)) #view data frame df team points assists rebounds 1 A 19 4 9 2 A 14 5 7 3 A 14 5 7 4 B 29 4 6 5 B 25 12 10 6 B 30 10 11
Example 1: Select One Row by Index
The following code shows how to select only the third row in the data frame:
#select third row
df[3, ]
team points assists rebounds
3 A 14 5 7
Only the values from the third row are returned.
Example 2: Select Multiple Rows by Index
The following code shows how to select multiple rows by index in the data frame:
#select third, fourth, and sixth rows
df[c(3, 4, 6), ]
team points assists rebounds
3 A 14 5 7
4 B 29 4 6
6 B 30 10 11
Only the values from the third, fourth, and sixth rows are returned.
Example 3: Select Range of Rows by Index
The following code shows how to select rows 2 through 5 in the data frame:
#select rows 2 through 5
df[2:5, ]
team points assists rebounds
2 A 14 5 7
3 A 14 5 7
4 B 29 4 6
5 B 25 12 10
All values for rows 2 through 5 are returned.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Append Rows to a Data Frame in R
How to Remove Duplicate Rows in R
How to Sum Specific Rows in R