Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the number of levels of all factors in a dataframe

Tags:

r

I'm attempting to create a list or df that contains, for all factors within a data frame, the number of levels of the factor.

So, it appears I need to first identify the factors (using is.factor()) and then count the number of levels for each (using length())

I was using sapply, but can't get what I am looking for.

Any help would be appreciated.

Here's what I've done so far:

fac <- sapply(cf_nm, function(x) is.factor(x)  )
fac <- cf_nm[fac]

And I could simply count the levels here - but I was hoping for a more eloquent way of doing what I'd like.

like image 421
gh0strider18 Avatar asked Dec 24 '22 22:12

gh0strider18


1 Answers

I believe you are looking for nlevels not length for the number of levels.

Here is a quick solution.

sapply(df1[,sapply(df1, is.factor)], nlevels)
like image 82
cdeterman Avatar answered Feb 09 '23 00:02

cdeterman