Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i rapidly explore the classes of all columns in a dataframe?

Tags:

dataframe

r

I want to rapidly explore the classes of columns in a dataframe, I made this function to print the columns names and arrange them by their class. I want it to tell me the numbers of the columns which aren't of class factor.

columnsclass<-function (x){
a<-vector()
b<-vector(mode="character")
c<-vector
c=0
for (i in 1:dim(x)[2]){
a[i]<-paste(class(x[,i]),names(x)[i],sep="--")
if (class(x[,i])!= "factor"){
c<-c+1
b[c]<<-i
}}
#1st print
print(sort(a))
#2nd print
print(paste("columns that aren't factors are number:",paste(b,collapse=","),collapse="  "))    
}

However when i run it, it doesn't do the #2nd print though the code is already working.

> columnsclass(cars) 
[1] "numeric--dist"  "numeric--speed"
[1] "columns that aren't factors are number: "
#it doesn't print the numbers of columns of class factor but if i run it separately ,it  runs
> print(paste("columns that aren't factors are   number:",paste(b,collapse=","),collapse="  "))
[1] "columns that aren't factors are number: 1,2"
like image 366
Elmahy Avatar asked Jan 01 '26 02:01

Elmahy


2 Answers

What about the str function?

library(datasets)
data(iris)
str(iris)
like image 55
landau Avatar answered Jan 02 '26 16:01

landau


Here's a function that takes into account Pierre's comments, but simplifies a's calculation as well:

columnsclass <- function(x){
  nm <- sapply(x, class)
  a <- paste(nm, names(nm), sep = "--")
  b <- which(!sapply(x, is.factor))
  # 1st print
  print(sort(a))
  # 2nd print
  print(paste("columns that aren't factors are number:", 
    paste(b, collapse = ","), collapse = "  "))    
}
> columnsclass(cars)
[1] "numeric--dist"  "numeric--speed"
[1] "columns that aren't factors are number: 1,2"
like image 44
mlegge Avatar answered Jan 02 '26 15:01

mlegge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!