How to remove a column from a data frame that contains same value in R?


If we have only one value in all of the rows of an R data frame then we might want to remove the whole column because the effect of that column will not make any sense in the data analysis objectives. Thus, instead of removing the column we can extract the columns that contains different values.

Example

 Live Demo

set.seed(1001)
x1<-sample(0:1,20,replace=TRUE)
x2<-rep(5,20)
x3<-sample(0:5,20,replace=TRUE)
x4<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4)
df1

Output

  x1 x2 x3 x4
1  0 5  1  6
2  0 5  1  4
3  0 5  3  7
4  0 5  2  5
5  1 5  3  5
6  0 5  0  5
7  1 5  1  7
8  0 5  5  5
9  1 5  5  4
10 1 5  2  1
11 1 5  4  6
12 1 5  5  8
13 1 5  0  4
14 1 5  1  9
15 1 5  2  9
16 0 5  5  8
17 0 5  1  6
18 0 5  1  4
19 1 5  3  7
20 0 5  4  2

Removing column that contains 5 −

Example

df1[,c(1,3,4)]

Output

  x1 x3 x4
1  0 1  6
2  0 1  4
3  0 3  7
4  0 2  5
5  1 3  5
6  0 0  5
7  1 1  7
8  0 5  5
9  1 5  4
10 1 2  1
11 1 4  6
12 1 5  8
13 1 0  4
14 1 1  9
15 1 2  9
16 0 5  8
17 0 1  6
18 0 1  4
19 1 3  7
20 0 4  2

Let’s have a look at another example −

Example

 Live Demo

y1<-sample(1:3,20,replace=TRUE)
y2<-sample(1:5,20,replace=TRUE)
y3<-rep(1,20)
y4<-sample(1:2,20,replace=TRUE)
y5<-sample(1:6,20,replace=TRUE)
y6<-sample(1:8,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4,y5,y6)
df2

Output

  y1 y2 y3 y4 y5 y6
1  3 2   1 1   3 1
2  2 2   1 2   3 5
3  2 5   1 1   2 6
4  2 4   1 1   4 6
5  1 1   1 1   1 4
6  1 2   1 1   3 6
7  1 3   1 2   5 2
8  3 2   1 2   5 1
9  1 3   1 1   3 6
10 3 1   1 2   6 1
11 3 3   1 2   4 2
12 2 4   1 2   5 5
13 3 5   1 2   4 7
14 3 2   1 1   1 5
15 3 1   1 2   3 1
16 2 4   1 2   5 5
17 2 3   1 2   3 6
18 3 4   1 1   1 6
19 1 1   1 1   6 5
20 1 3   1 1   6 1

Removing column 3 from data frame df2 −

Example

df2[,c(1,2,4,5,6)]

Output

  y1 y2 y4 y5 y6
1  3 2   1 3   1
2  2 2   2 3   5
3  2 5   1 2   6
4  2 4   1 4   6
5  1 1   1 1   4
6  1 2   1 3   6
7  1 3   2 5   2
8  3 2   2 5   1
9  1 3   1 3   6
10 3 1   2 6   1
11 3 3   2 4   2
12 2 4   2 5   5
13 3 5   2 4   7
14 3 2   1 1   5
15 3 1   2 3   1
16 2 4   2 5   5
17 2 3   2 3   6
18 3 4   1 1   6
19 1 1   1 6   5
20 1 3   1 6   1

Updated on: 17-Oct-2020

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements