R : want to delete a level from a factor variable with r


#1

Hello I have a table with a facor variable with 3 levels. I make a subset of it where i keep only 2 levels.
the point is that the varibale keep showing 3 levels
test<-data[bloc!=1,]
levels (test$class)
[1] “class1” “class2” "class3"
summary(test$class)
class1 class2 class3
162 37 0
Any idea how I can fix that ?
TIA


#2

@loubna181 can you please upload the …data file…so that i may have a look at what you are trying to do ?


#3

My data set is quite big. It contains 9 numeric varibales and one factor variable called class. This variable has three levels : class1, class2 and class3.
I made a subset of the data set keeping only two possible values for class variable : class1 and class2
the problem is when I check the levels of the class variable in the subset table it still shows 3 classes.
(I need this new table for a classification analysis)
thanks


#4

@loubna181
yeah i ran this on a sample dataset and found it to be true. It appears like whenever you subset from a dataset the factor properties of the original dataset are preserved.
However there is a work around.

convert your class variable to a character object, subset it and then convert it back to factor.
I tried it, it gave me a factor level of just two.

Hope this helps.


#5

Yes it works. I should have think about it lol. Thanks a lot :slight_smile:


#6

#7

#8

@loubna181 please mark it as accepted solution , if it worked :slight_smile:


#9

Note: You can achieve this using a single command droplevels. It will take care of all the factor variables in the dataframe.

test <- data[bloc!=1,] test <- droplevels(test) levels (test$class) summary (test$class)


#10

You can use:
test$class<-factor(test$class)
hope it will work!!
Thanks.


#11

@Tapojyoti_Paul 's answer is the most widely used method