0

I have 3 data frames x,y and z, and I would like to create a for loop in a function to be able to get the class of each column.

Let's say I name my function ColumnClass, I need the result to be as follow when I type ColumnClass(x)

x-- The class of the column A is : integer

x-- The class of the column B is : character

and so on ... same thing if I type ColumnClass(y) or ColumnClass(z)

Do you have any idea on how I can do that?

Please keep in mind that I just started using R, so any help is welcomed.

Thank you,

RLearner
  • 11
  • 1

2 Answers2

1

Maybe this could help you:

colClass <- function(dat){
  ind <- seq_len(ncol(dat))
  Names <- names(dat)
  colClass <- sapply(dat, class)

  invisible(
    sapply(ind, function(i){
      cat("The class of the column", Names[i],"is:", colClass[i], "\n")
      }
      )
    )
}

> # E X A M P L E S 
> colClass(iris)
The class of the column Sepal.Length is: numeric 
The class of the column Sepal.Width is: numeric 
The class of the column Petal.Length is: numeric 
The class of the column Petal.Width is: numeric 
The class of the column Species is: factor 

> colClass(mtcars)
The class of the column mpg is: numeric 
The class of the column cyl is: numeric 
The class of the column disp is: numeric 
The class of the column hp is: numeric 
The class of the column drat is: numeric 
The class of the column wt is: numeric 
The class of the column qsec is: numeric 
The class of the column vs is: numeric 
The class of the column am is: numeric 
The class of the column gear is: numeric 
The class of the column carb is: numeric 

E D I T Based on @Frank 's comment you can avoid one sapply and use sprintf:

colClass2 <- function(dat){
  cat(sprintf("The class of the column %s is: %s \n", 
              names(dat), 
              sapply(dat, class)))
}
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

We can create a function

ColumnClass <- function(dat, col) {
       class(dat[[col]])
  }

If we want to pass without quotes

ColumnClass <- function(dat, col) {
   class(dat[[deparse(substitute(col))]])
 }

If we need to get the class of all the columns

ColumnClassAll <- function(dat) {
     sapply(dat, class)
}
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Once the function is created, how can I insert the loop so I can get the sentence : The class of the column A is : integer for each column of the table? – RLearner Oct 18 '18 at 15:39
  • @RLearner You may need to `paste` the string with the output from the function – akrun Oct 18 '18 at 15:40