- Related Questions & Answers
- How to collapse factor levels in an R data frame?
- How to subset factor columns in an R data frame?
- How to extract the factor levels from factor column in an R data frame?
- How to combine the levels of a factor variable in an R data frame?
- How to create scatterplot for factor levels in an R data frame?
- How to create a subset for a factor level in an R data frame?
- How to find the cumulative sum for factor levels in an R data frame?
- How to find the sum by distinct column for factor levels in an R data frame?
- What are levels in a column of a data frame in R?
- How to sum a variable by factor levels in R?
- How to convert factor levels into character in R?
- How to subset a data frame by excluding a specific text value in an R data frame?
- How to subset a data frame based on a vector values in R?
- How to find the number of levels in R for a factor column?
- How to create a subset of a data frame in R without using column names?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

There are two ways to do drop the factor levels in a subset of a data frame, first one is by using factor function and another is by using lapply.

> df <- data.frame(alphabets=letters[1:10], numbers=seq(0:9)) > levels(df$alphabets) [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" > subdf <- subset(df, numbers <= 6) > subdf alphabets numbers 1 a 1 2 b 2 3 c 3 4 d 4 5 e 5 6 f 6 > levels(subdf$alphabets) [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

Although we have created a subset but the level of factor variable alphabets still showing 10 levels. If we want to drop the factor levels then it can be done by

Using factor function

> subdf$alphabets <- factor(subdf$alphabets) > levels(subdf$alphabets) [1] "a" "b" "c" "d" "e" "f"

Using lapply

> subdf[] <- lapply(subdf, function(x) if(is.factor(x)) factor(x) else x) > levels(subdf$alphabets) [1] "a" "b" "c" "d" "e" "f"

Advertisements