如何获得数据框架中所有列的类?

找出数据框架中每个列是什么类的简单方法是什么?

148876 次浏览

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))

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)

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"