There are three common ways to drop columns from a data frame in R by name:
Method 1: Use Base R
#drop col2 and col4 from data frame
df_new
Method 2: Use dplyr
library(dplyr) #drop col2 and col4 from data frame df_new % select(-c(col2, col4))
Method 3: Use data.table
library(data.table) #convert data frame to data table dt #drop col2 and col4 from data frame dt[, c('col2', 'col4'):=NULL]
The following examples show how to use each method in practice with the following data frame in R:
#create data frame
df frame(team=c('A', 'A', 'B', 'B', 'C', 'C', 'C', 'D'),
points=c(12, 15, 22, 29, 35, 24, 11, 24),
rebounds=c(10, 4, 4, 15, 14, 9, 12, 8),
assists=c(7, 7, 5, 8, 19, 14, 11, 10))
#view data frame
df
team points rebounds assists
1 A 12 10 7
2 A 15 4 7
3 B 22 4 5
4 B 29 15 8
5 C 35 14 19
6 C 24 9 14
7 C 11 12 11
8 D 24 8 10
Example 1: Drop Columns by Name Using Base R
The following code shows how to drop the points and assists columns from the data frame by using the subset() function in base R:
#create new data frame by dropping points and assists columns
df_new #view new data frame
df_new
team rebounds
1 A 10
2 A 4
3 B 4
4 B 15
5 C 14
6 C 9
7 C 12
8 D 8
Notice that the points and assists columns have both been dropped from the new data frame.
Example 2: Drop Columns by Name Using dplyr
The following code shows how to drop the points and assists columns from the data frame by using the select() function in the dplyr package:
library(dplyr)
#create new data frame by dropping points and assists columns
df_new % select(-c(points, assists))
#view new data frame
df_new
team rebounds
1 A 10
2 A 4
3 B 4
4 B 15
5 C 14
6 C 9
7 C 12
8 D 8
Notice that the points and assists columns have both been dropped from the new data frame.
Example 3: Drop Columns by Name Using data.table
The following code shows how to drop the points and assists columns from the data frame by setting both columns equal to NULL using the data.table package:
library(data.table)
#convert data frame to data table
dt #drop points and assists columns
dt[, c('points', 'assists'):=NULL]
#view updated data table
dt
team rebounds
1: A 10
2: A 4
3: B 4
4: B 15
5: C 14
6: C 9
7: C 12
8: D 8
Notice that the points and assists columns have both been dropped from the new data table.
Note: All three methods produce the same result, but the dplyr and data.table methods will tend to be faster when working with extremely large datasets.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Remove Columns with NA Values in R
How to Reorder Columns in R
How to Rename Columns in R