How to remove a column from an R data frame?

R ProgrammingServer Side ProgrammingProgramming

This can be easily done by using subset function.

Example

> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df
x  y  z  a
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19
5 5 10 15 20

To remove only one column

> df <- subset (df, select = -x)
> df
y z a
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20

To remove two columns

> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x,y))
> df
z a
1 11 16
2 12 17
3 13 18
4 14 19
5 15 20

To remove a range of columns

> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x:z))
> df
a
1 16
2 17
3 18
4 19
5 20

To remove separate columns

> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x,z:a))
> df
y
1 6
2 7
3 8
4 9
5 10
raja
Published on 06-Jul-2020 14:29:55
Advertisements