Some data:
insurance <- data.frame( int = 1:5, fact1 = letters[1:5], fact2 = factor(1:5), fact3 = LETTERS[3:7] )
I would use sapply , like you, but in combination with is.factor , to return a logical vector:
is.fact <- sapply(insurance, is.factor)
Then use [ to extract these columns:
factors.df <- insurance[, is.fact]
Finally, to get levels, use lapply :
lapply(factors.df, levels) # $fact1 # [1] "a" "b" "c" "d" "e" # # $fact2 # [1] "1" "2" "3" "4" "5" # # $fact3 # [1] "C" "D" "E" "F" "G"
You can also find str(insurance) interesting as a short summary.
flodel
source share