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"
What about the str function?
library(datasets)
data(iris)
str(iris)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With