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

R

R Problem Overview


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

R Solutions


Solution 1 - R

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

Solution 2 - R

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.

Solution 3 - R

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

unlist(lapply(mtcars,class))

Solution 4 - R

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"

Solution 5 - R

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle BrandtView Question on Stackoverflow
Solution 1 - RKyle BrandtView Answer on Stackoverflow
Solution 2 - RRohit SainiView Answer on Stackoverflow
Solution 3 - RSeyma KalayView Answer on Stackoverflow
Solution 4 - RAlecView Answer on Stackoverflow
Solution 5 - RAlexBView Answer on Stackoverflow