Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find unused factor levels?

Tags:

enums

r

r-factor

I have data frame with "State" column, which is a factor with US State.

Not all states are present among values, while all states are among factor levels.

How to find factor levels, which are never used in the data frame?

like image 704
Suzan Cioc Avatar asked May 03 '15 22:05

Suzan Cioc


People also ask

How do you find a factor level?

The number of levels of a factor or independent variable is equal to the number of variations of that factor that were used in the experiment. If an experiment compared the drug dosages 50 mg, 100 mg, and 150 mg, then the factor "drug dosage" would have three levels: 50 mg, 100 mg, and 150 mg.

How do you get rid of a factor level?

The droplevels() function in R can be used to drop unused factor levels. This function is particularly useful if we want to drop factor levels that are no longer used due to subsetting a vector or a data frame. where x is an object from which to drop unused factor levels.

How do I drop unused levels in R?

droplevels in R with examples, To remove unneeded factor levels, use R's droplevels() function. This function comes in handy when we need to get rid of factor levels that are no longer in use as a result of subsetting a vector or a data frame.

What is the Droplevels function in R?

The droplevels R function removes unused levels of a factor. The function is typically applied to vectors or data frames.


1 Answers

Try:

# A toy factor variable:
f <- factor(letters[1:2], levels = letters[1:4])
f
[1] a b
Levels: a b c d
levels(f)
[1] "a" "b" "c" "d"

To see the unused levels:

setdiff(levels(f), f)
[1] "c" "d"
like image 122
DatamineR Avatar answered Sep 22 '22 16:09

DatamineR