Was it helpful?

Question

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

R ProgrammingServer Side ProgrammingProgramming

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 <- data.frame(
   Var1 =1:10,
   Var2 =11:20,
   Var3 =21:30,
   Var4 =31:40
)
We can drop columns Var1 and Var2 using the below code:
drops <- c("Var1","Var2")
> 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 <- c("Var3", "Var4")
> 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
raja
Published on 06-Jul-2020 16:07:48
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top