'Count how many times each class occurs in a dataframe

What is the best way to get a count of all classes in a dataframe?

I know that I could use a combination of lapply and table, but wondering if there are better ways. I am looking for an output like below.

as.data.frame(table(unlist(lapply(iris, class))))

#     Var1 Freq
#1  factor    1
#2 numeric    4

Additionally, what is the best way to handle multiple classes in a dataframe? For example, using the nycflights13, I know I could do something like this.

as.data.frame(table(unlist(
  lapply(nycflights13::weather, function(x)
    paste(class(x), collapse = ","))
))) %>%
  separate(col = "Var1", into = c("Var1", "Var2"), sep = ",", fill = "right")

#       Var1   Var2 Freq
#1 character   <NA>    1
#2   integer   <NA>    4
#3   numeric   <NA>    9
#4   POSIXct POSIXt    1
r


Solution 1:[1]

when df is a data.table, I often this use this: df[,table(sapply(.SD,class))]. In the case of iris, this returns:

 factor numeric 
      1       4 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 langtang