Table of Contents
Removing multiple rows in R can be done easily using the subset() function. This function takes the data frame and a set of conditions as input. The conditions specify which rows to remove and the function will then return a new data frame with the rows removed according to those conditions. Examples of how to use this function are included in the article.
You can use one of the following methods to remove multiple rows from a data frame in R:
Method 1: Remove Specific Rows
#remove rows 2, 3, and 4
new_df <- df[-c(2, 3, 4), ]
Method 2: Remove Range of Rows
#remove rows 2 through 5
new_df <- df[-c(2:5), ]
Method 3: Remove Last N Rows
#remove rows 4 through last row new_df <- df[-c(4:nrow(df)), ]
The following examples show how to use each of these methods in practice with the following data frame:
#create data frame df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F'), points=c(99, 90, 86, 88, 95, 99), assists=c(33, 28, 31, 39, 34, 24)) #view data frame df team points assists 1 A 99 33 2 B 90 28 3 C 86 31 4 D 88 39 5 E 95 34 6 F 99 24
Example 1: Remove Specific Rows
The following code shows how to remove rows 2, 3, and 4 from the data frame:
#define new data frame with rows 2, 3, 4 removed
new_df <- df[-c(2, 3, 4),]
#view new data frame
new_df
team points assists
1 A 99 33
5 E 95 34
6 F 99 24
Notice that rows 2, 3, and 4 have all been removed from the data frame.
Example 2: Remove Range of Rows
The following code shows how to remove rows in the range of 2 through 5:
#define new data frame with rows 2 through 5 removed
new_df <- df[-c(2:5),]
#view new data frame
new_df
team points assists
1 A 99 33
6 F 99 24
Notice that rows 2, 3, 4, and 5 have been removed.
Example 3: Remove Last N Rows
The following code shows how to remove rows 4 through the last row:
#remove rows 4 through last row
new_df <- df[-c(4:nrow(df)), ]
#view new data frame
new_df
team points assists
1 A 99 33
2 B 90 28
3 C 86 31
Notice that row 4 and all rows after it have been removed.
The following tutorials explain how to perform other common operations in R: