[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


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

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.


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

unlist(lapply(mtcars,class))

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)

Questions with r tag:

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean? Saving a high resolution image in R Change bar plot colour in geom_bar with ggplot2 in r Converting data frame column from character to numeric Extract Month and Year From Date in R How to combine two lists in R Extract year from date Ifelse statement in R with multiple conditions R dplyr: Drop multiple columns Remove legend ggplot 2.2 Remove all of x axis labels in ggplot how to remove multiple columns in r dataframe? Aggregate multiple columns at once Changing fonts in ggplot2 How to specify "does not contain" in dplyr filter how to use the Box-Cox power transformation in R Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe Having trouble setting working directory Coerce multiple columns to factors at once How to declare a vector of zeros in R Create empty data frame with column names by assigning a string vector? Explain ggplot2 warning: "Removed k rows containing missing values" R for loop skip to next iteration ifelse Error: package or namespace load failed for ggplot2 and for data.table How do I change the default library path for R packages Select first and last row from grouped data R * not meaningful for factors ERROR Error: could not find function "%>%" Raise to power in R In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Error - replacement has [x] rows, data has [y] Merge r brings error "'by' must specify uniquely valid columns" Non-numeric Argument to Binary Operator Error in R Convert row names into first column Append data frames together in a for loop Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis R Markdown - changing font size and font type in html output Replace all occurrences of a string in a data frame How to convert dataframe into time series? Sum across multiple columns with dplyr Removing NA observations with dplyr::filter()