How can I drop unused levels from a data frame?

后端 未结 3 1557
执念已碎
执念已碎 2020-12-04 15:50

Given the following mock data:

set.seed(123)
x <- data.frame(let = sample(letters[1:5], 100, replace = T), 
                num = sample(1:10, 100, replac         


        
3条回答
  •  清歌不尽
    2020-12-04 16:18

    Adding to Hong Ooi's answer, here is an example I found from R-Bloggers.

    # Create some fake data
    x <- as.factor(sample(head(colors()),100,replace=TRUE))
    levels(x)
    x <- x[x!="aliceblue"]
    levels(x) # still the same levels
    table(x) # even though one level has 0 entries!
    
    The solution is simple: run factor() again:
    x <- factor(x)
    levels(x)
    

提交回复
热议问题