About this question
I want to drop column r in the data frame. Please help me with a solution.
I want to drop column r in the data frame. Please help me with a solution.
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Java Expert
Answered on Jul 26, 2021
We can Drop Columns by name in a data frame using the following two methods:
Create a data frame
The following code creates a sample data frame which we will use for demonstration.
set.seed(556)
mydata <- data.frame(m=letters[1:5], x=runif(5,10,50), y=sample(5), z=rnorm(5))# Delete column by name
Method I :
One of the easiest ways to drop columns is by using the subset() function.
The following code tells R to drop variables x and z.
The '-' sign indicates dropping variables.
Note: Don't specify the variable names in quotes when using the subset() function.
df = subset(mydata, select = -c(x,z) )
> mydata
m x y z
1 a 33.83910 2 -1.02569136
2 b 23.50851 3 0.59367584
3 c 22.91966 1 -0.06436851
4 d 33.18065 4 -0.04719129
5 e 13.79128 5 -1.80186137
> df
m y
1 a 2
2 b 3
3 c 1
4 d 4
5 e 5
Method II :The function names() returns all the column names and the '!' sign indicates negation.
drop <- c("x","z") #we are creating a character vector named drop in which we are storing column names x and z
df = mydata[,!(names(mydata) %in% drop)] #Selecting all the variables except the column names specified in the vector drop. The '!' sign indicates negation.
> df
m y
1 a 2
2 b 3
3 c 1
4 d 4
5 e 5
It can also be written like : df = mydata[,!(names(mydata) %in% c("x","z"))]
> set.seed(556)
> mydata <- data.frame(m=letters[1:5], x=runif(5,10,50), y=sample(5), z=rnorm(5))
> df = mydata[,!(names(mydata) %in% c("x","z"))]
> df
m y
1 a 2
2 b 3
3 c 1
4 d 4
5 e 5
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Java interview questions, answered
Guides, tips and career advice on Java from JanBask experts.
Java Frequently Asked J2EE Interview Questions and Answers You Must Read
Top 45 frequently asked Java J2EE interview questions to ace your interview. These J2EE questions are useful for freshers and…
Java Top 100+ Angular Interview Questions and Answers
Are you preparing for your next Angular interview? We have compiled the list of the top 100+ Angular Interview Questions &…
Java Top 51+ Simple Java Project Ideas for Beginners In 2025
Enhance your Java skills with our top 51+ project ideas! From beginner-friendly exercises to advanced applications, fuel your…
Java How Long Does It Takes To Learn Java?
Confused about How long does it take to learn Java ? Well, No worries! This blog will guide you with valuable information and…