How to get class of all the variables/columns of a data frame/matrix in R
Sanmeet Walia
Helping Enterprises Boost Their Marketing ROI with Digital Analytics
Yo,
At times we need to know the class of the variables of a data set. Certain classes are not compatible with certain functions. They don't like each other. And certain classes result is wrong interpretation of the data. So, you get the point, you need to know something with which you can get the class.
So here is the classy approach -
1. Create a new object
2. Use sapply function with class function on the Data frame
3. Marry step 1 and 2.
Tada -
NewOb <- sapply(YourDataTable,class)
Lets add some more utility. Suppose you want to extract variables only of a certain class. For this you will use the grep() function on the object created above.
Lets assume you want all the variables with class 'factor'. Here you go -
ClassFac<-grep("factor",NewOb)
This will feed the column numbers of the variables which are having "factor" class. You can now simply take the subset of your original data based on the column numbers you get from the grep() function.
SubData<-YourDataTable[,ClassFac]
Obrigada,
Sanmeet