简体   繁体   中英

Output the number of levels of all factors in a dataframe

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM