0
$\begingroup$

I am trying to use droplevels. First I create a subsect of my dataset where the value of attribute Rat must be different from 1 or 5. That value must be a factor. Then, I can see levels are "1", "2", "3", "4" and "5". As I use droplevels() nothing changes. How can I do properly? I wrote this code:

chocolate234 <- subset(chocolate, Rat!="1")
chocolate234 <- subset(chocolate234, Rat!="5")
droplevels(chocolate234$Rat)
$\endgroup$
1
$\begingroup$

Like most function in r, droplevels operates on your data but does not change it. The droplevels function returns a factor vector with the levels dropped, but it does not change the original vector. To do that, you need to assign the result of droplevels back to the original original vector. Here is an example:

# Building an example data.frame
set.seed(1234)
rating <- factor(as.character(sample(1:5, 100, replace = T)))
label <- sample(LETTERS, 100, replace = T) 
example <- data.frame(label = label, Rat = rating)
summary(example$Rat)
  1  2  3  4  5 
 25 26 17 17 15 

# Subsetting the data
example234 <- subset(example, Rat != "1")
example234 <- subset(example234, Rat != "5")
summary(example234$Rat)
  1  2  3  4  5 
  0 26 17 17  0 

# Dropping unused levels
droplevels(example234$Rat)
  [1] 4 4 4 4 2 4 3 4 3 2 2 2 2 2 2 2 2 3 3 2 2 3 4 2 2 3 4 2 4 2 3 4 3 2 4 2 4
  [38] 3 3 3 4 2 2 4 2 3 3 4 3 2 2 4 3 3 2 2 3 2 2 4
  Levels: 2 3 4
summary(example234$Rat)
  1  2  3  4  5 
  0 26 17 17  0 

# Reassigning the data with dropped levels
example234$Rat <- droplevels(example234$Rat)
summary(example234$Rat)
  2  3  4 
 26 17 17 

Notice in my example, like your attempt, if you just run droplevels on the data, it does not change the underlying data. However, if you assign the results of droplevels(example234$Rat) to example234$Rat, your underlying data has been properly changed.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you very much for your clear explanation! $\endgroup$ – user96624 Jun 1 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.