Return 矩阵中某种数据类型的列数

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

我必须创建一个函数 ncol_type(df, ty),其中 returns 类型为 ty 的 df 中的列数。

这是我目前的情况:

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)
    }
}

例如,如果我输入 n_col_type(df, "integer") 其中矩阵 df 有两列整数数据类型,我希望函数 return "2 ".

我不确定我做错了什么。谢谢

您可以 re-write 您的代码,只需使用 sum 并使用 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