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


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
levels (test$class)
[1] “class1” “class2” "class3"
class1 class2 class3
162 37 0
Any idea how I can fix that ?


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


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)


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.


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

closed #6

opened #7


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


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)


You can use:
hope it will work!!


@Tapojyoti_Paul 's answer is the most widely used method