How to subset a data frame by excluding a column using dplyr in R?


Subsetting is one of the commonly used technique which serves many different purposes depending on the objective of analysis. To subset a data frame by excluding a column with the help of dplyr package, we can follow the below steps −

  • Creating a data frame.
  • Subsetting the data frame by excluding a column with select function of dplyr package.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-rnorm(20)
x2<-rnorm(20)
Grp<-sample(c("A","B","C"),20,replace=TRUE)
df<-data.frame(x1,x2,Grp)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

         x1          x2  Grp
1   -0.97499365 1.1209623 B
2   0.17654062 -0.5108460 B
3   -1.37597227 0.6234678 B
4   -0.04213631 1.8470026 B
5  -0.54300975 -0.2474428 C
6   2.02651623 -1.0575005 A
7  -1.23452262 0.8279649  C
8   0.39798172 -0.4402006 C
9  -1.16629977 0.1835519  C
10  0.43068506 0.1726156  B
11  0.94398810 2.1765716  B
12  0.02955538 -0.2140563 B
13 -0.81368702 0.8287662  A
14 -0.63364653 1.7398114  B
15 -0.46805617 -0.7172697 A
16 -0.39318014 -0.8754293 A
17 -1.75739144 1.7773268 C
18  1.32307668 -0.6249176 C
19  0.83385016 1.1067398 B
20 -1.19528606 -1.0941674 B

Subsetting df by excluding a column

Loading dplyr package and subsetting the data frame df by excluding column Grp −

library(dplyr)
x1<-rnorm(20)
x2<-rnorm(20)
Grp<-sample(c("A","B","C"),20,replace=TRUE)
df<-data.frame(x1,x2,Grp)
df<-df%>%select(-Grp)
df

Output

         x1       x2
1 -0.97499365 1.1209623
2 0.17654062 -0.5108460
3 -1.37597227 0.6234678
4 -0.04213631 1.8470026
5 -0.54300975 -0.2474428
6 2.02651623 -1.0575005
7 -1.23452262 0.8279649
8 0.39798172 -0.4402006
9 -1.16629977 0.1835519
10 0.43068506 0.1726156
11 0.94398810 2.1765716
12 0.02955538 -0.2140563
13 -0.81368702 0.8287662
14 -0.63364653 1.7398114
15 -0.46805617 -0.7172697
16 -0.39318014 -0.8754293
17 -1.75739144 1.7773268
18 1.32307668 -0.6249176
19 0.83385016 1.1067398
20 -1.19528606 -1.0941674

Updated on: 13-Aug-2021

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements