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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With