Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 781
Kyle Brandt Avatar asked May 18 '12 23:05

Kyle Brandt


People also ask

How do I find duplicate columns in R?

The second method to find and remove duplicated columns in R is by using the duplicated() function and the t() function. This method is similar to the previous method. However, instead of creating a list, it transposes the data frame before applying the duplicated() function.

How do I find the class of data in R?

To determine the class of any R object's “internal” type, use the class() function. If the object does not have a class attribute, it has an implicit class, prominently “matrix“, “array“, “function” or “numeric,” or the result of typeof(x). The class() function is robust.

How do I duplicate multiple columns in R?

The best way to replicate columns in R is by using the CBIND() function and the REP() function. First, you use the REP() function to select a column and create one or more copies. Then, you use the CBIND() function to merge the original dataset and the replicated columns into a single data frame.


2 Answers

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 
like image 51
Kyle Brandt Avatar answered Oct 21 '22 10:10

Kyle Brandt


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.

like image 36
Rohit Saini Avatar answered Oct 21 '22 11:10

Rohit Saini