There are five common ways to extract rows from a data frame in R:
Method 1: Extract One Row by Position
#extract row 2
df[2, ]
Method 2: Extract Multiple Rows by Position
#extract rows 2, 4, and 5
df[c(2, 4, 5), ]
Method 3: Extract Range of Rows
#extract rows in range of 1 to 3
df[1:3, ]
Method 4: Extract Rows Based on One Condition
#extract rows where value in column1 is greater than 10
df[df$column1 > 10, ]
Method 5: Extract Rows Based on Multiple Conditions
#extract rows where column1 > 10 and column2 > 5
df[df$column1 > 10 & df$column2 > 5, ]
#extract rows where column1 > 10 or column2 > 5
df[df$column1 > 10 | df$column2 > 5, ]
The following examples show how to use each method with the following data frame:
#create data frame df frame(team=c('A', 'B', 'C', 'D', 'E'), points=c(99, 90, 86, 88, 95), assists=c(33, 28, 31, 39, 34), rebounds=c(30, 28, 24, 24, 28)) #view data frame df team points assists rebounds 1 A 99 33 30 2 B 90 28 28 3 C 86 31 24 4 D 88 39 24 5 E 95 34 28
Example 1: Extract One Row by Position
The following code shows how to extract only row 2 from the data frame:
#extract row 2
df[2, ]
team points assists rebounds
2 B 90 28 28
Example 2: Extract Multiple Rows by Position
The following code shows how to extract rows 2, 4, and 5 from the data frame:
#extract rows 2, 4, and 5
df[c(2, 4, 5), ]
team points assists rebounds
2 B 90 28 28
4 D 88 39 24
5 E 95 34 28
Example 3: Extract Range of Rows
The following code shows how to extract rows in the range from 1 to 3:
#extract rows in range of 1 to 3
df[1:3, ]
team points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
Example 4: Extract Rows Based on One Condition
The following code shows how to extract the rows where the value in the points column is greater than 90:
#extract rows where value in points column is greater than 90
df[df$points > 90, ]
team points assists rebounds
1 A 99 33 30
5 E 95 34 28
Example 5: Extract Rows Based on Multiple Conditions
The following code shows how to extract the rows where the value in the points column is greater than 90:
#extract rows where points is greater than 90 and assists is greater than 33
df[df$points > 90 & df$assists > 33, ]
team points assists rebounds
5 E 95 34 28
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Remove Duplicate Rows in R
How to Remove Multiple Rows in R
How to Count Number of Rows in R