rfunctionfor-loopdataframecolumn-types

Return number of columns of a certain data type in a matrix


I have to create a function ncol_type(df, ty) which returns the number of columns in df of type ty.

Here is what I have so far:

ncol_type = function(df, ty) {
    for (col_name in names(df)) {
        col_vector_class <- class(df[,col_name])
        c == 0
        if (col_vector_class == ty) {
            c = c + 1
        }
     return(c)
    }
}

For example, if I input n_col_type(df, "integer") where the matrix df has two columns of the integer data type, I want the function to return "2".

I'm not sure what I am doing wrong. Thanks.


Solution

  • You can re-write your code and simply use sum and iterate with sapply

    ncol_type <- function(df, ty){
      sum(sapply(df, function(x) class(x)==ty))
    }
    
    ncol_type(iris, "factor")
    [1] 1
    ncol_type(iris, "numeric")
    [1] 4