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

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

This question is related to r

The answer is


I wanted a more compact output than the great answers above using lapply, so here's an alternative wrapped as a small function.

# Example data
df <-
    data.frame(
        w = seq.int(10),
        x = LETTERS[seq.int(10)],
        y = factor(letters[seq.int(10)]),
        z = seq(
            as.POSIXct('2020-01-01'),
            as.POSIXct('2020-10-01'),
            length.out = 10
        )
    )

# Function returning compact column classes
col_classes <- function(df) {
    t(as.data.frame(lapply(df, function(x) paste(class(x), collapse = ','))))
}

# Return example data's column classes
col_classes(df)
  [,1]            
w "integer"       
x "character"     
y "factor"        
z "POSIXct,POSIXt"

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

Hello was looking for the same, and it could be also

unlist(lapply(mtcars,class))

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.