How to get list of all columns except one or more columns from an R data frame?


Sometimes, we want to use some columns of an R data frame for analysis, therefore, it is better to get a list of all the columns that we need. In this way, we don’t have to worry about the column operations, if required because we will be having only necessary columns. To get the list of all columns except one or more columns can be done with the help of single square brackets.

Example

Consider the below data frame −

set.seed(100)
x1 <-LETTERS[1:20]
x2 <-sample(1:100,20)
x3 <-sample(1:10,20,replace=TRUE)
x4 <-rnorm(20)
df <-data.frame(x1,x2,x3,x4)
df

Output

   x1  x2  x3  x4
1 A 74 2 -0.69001432
2 B 89 3 -0.22179423
3 C 78 4 0.18290768
4 D 23 4 0.41732329
5 E 86 4 1.06540233
6 F 70 5 0.97020202
7 G 4 7 -0.10162924
8 H 55 9 1.40320349
9 I 95 4 -1.77677563
10 J 7 2 0.62286739
11 K 91 6 -0.52228335
12 L 93 7 1.32223096
13 M 43 1 -0.36344033
14 N 82 6 1.31906574
15 O 61 9 0.04377907
16 P 12 9 -1.87865588
17 Q 51 9 -0.44706218
18 R 72 6 -1.73859795
19 S 18 8 0.17886485
20 T 25 7 1.89746570

Example

df[,1]
[1] A B C D E F G H I J K L M N O P Q R S T
Levels: A B C D E F G H I J K L M N O P Q R S T
df[,1:3]

Output

x1 x2 x3
1 A 74 2
2 B 89 3
3 C 78 4
4 D 23 4
5 E 86 4
6 F 70 5
7 G 4 7
8 H 55 9
9 I 95 4
10 J 7 2
11 K 91 6
12 L 93 7
13 M 43 1
14 N 82 6
15 O 61 9
16 P 12 9
17 Q 51 9
18 R 72 6
19 S 18 8
20 T 25 7

Example

df[,c(2,4)]

Output

df[,c(2,4)]

Example

   x2    x4
1 74 -0.69001432
2 89 -0.22179423
3 78 0.18290768
4 23 0.41732329
5 86 1.06540233
6 70 0.97020202
7 4 -0.10162924
8 55 1.40320349
9 95 -1.77677563
10 7 0.62286739
11 91 -0.52228335
12 93 1.32223096
13 43 -0.36344033
14 82 1.31906574
15 61 0.04377907
16 12 -1.87865588
17 51 -0.44706218
18 72 -1.73859795
19 18 0.17886485
20 25 1.89746570

Example

df[,-c(2,4)]

Output

x1 x3
1 A 2
2 B 3
3 C 4
4 D 4
5 E 4
6 F 5
7 G 7
8 H 9
9 I 4
10 J 2
11 K 6
12 L 7
13 M 1
14 N 6
15 O 9
16 P 9
17 Q 9
18 R 6
19 S 8
20 T 7

Example

df[,-1]

Output

x2    x3    x4
1 74 2 -0.69001432
2 89 3 -0.22179423
3 78 4 0.18290768
4 23 4 0.41732329
5 86 4 1.06540233
6 70 5 0.97020202
7 4 7 -0.10162924
8 55 9 1.40320349
9 95 4 -1.77677563
10 7 2 0.62286739
11 91 6 -0.52228335
12 93 7 1.32223096
13 43 1 -0.36344033
14 82 6 1.31906574
15 61 9 0.04377907
16 12 9 -1.87865588
17 51 9 -0.44706218
18 72 6 -1.73859795
19 18 8 0.17886485
20 25 7 1.89746570

Example

df[,-4]

Output

x1 x2 x3
1 A 74 2
2 B 89 3
3 C 78 4
4 D 23 4
5 E 86 4
6 F 70 5
7 G 4 7
8 H 55 9
9 I 95 4
10 J 7 2
11 K 91 6
12 L 93 7
13 M 43 1
14 N 82 6
15 O 61 9
16 P 12 9
17 Q 51 9
18 R 72 6
19 S 18 8
20 T 25 7

Updated on: 21-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements