How to drop data frame columns in R by using column name?

Columns of a data frame can be dropped by creating an object of columns that we want to drop or an object of columns that we want to keep.

Example

> df  df[ , !(names(df) %in% drops)]
Var3 Var4
1 21 31
2 22 32
3 23 33
4 24 34
5 25 35
6 26 36
7 27 37
8 28 38
9 29 39
10 30 40

Alternatively, we can do the same by using keeps function that will keep the variables we want to have in our data frame as shown below −

> keeps  df[keeps]
Var3 Var4
1 21 31
2 22 32
3 23 33
4 24 34
5 25 35
6 26 36
7 27 37
8 28 38
9 29 39
10 30 40
Updated on: 2020-07-06T12:39:01+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements