How do I get the classes of all columns in a data frame?

86

What is an easy way to find out what class each column is in a data frame is?

This question is tagged with r

~ Asked on 2012-05-18 23:59:04

The Best Answer is


93

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

~ Answered on 2012-05-18 23:59:26


28

You can simple make use of lapply or sapply builtin functions.

lapply will return you a list -

lapply(dataframe,class)

while sapply will take the best possible return type ex. Vector etc -

sapply(dataframe,class)

Both the commands will return you all the column names with their respective class.

~ Answered on 2018-07-05 06:22:02


Most Viewed Questions: