Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 返回矩阵中特定数据类型的列数_R_Function_For Loop_Dataframe_Column Types - Fatal编程技术网

R 返回矩阵中特定数据类型的列数

R 返回矩阵中特定数据类型的列数,r,function,for-loop,dataframe,column-types,R,Function,For Loop,Dataframe,Column Types,我必须创建一个函数ncol_type(df,ty),它返回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

我必须创建一个函数ncol_type(df,ty),它返回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)
    }
}
ncol\u类型=函数(df,ty){
用于(姓名中的姓名(df)){

col_vector_class您可以重新编写代码,只需使用
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

ncol\u type您可以重新编写代码,只需使用
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

ncol\u type A
matrix
只能包含一种类型。您最可能的意思是
dataframe
。这样您就可以正确使用术语了。@andrelrico谢谢Andre。我将更改标记。我将使用类似于
sum(sapply(df,is.integer))的标记。
当然,您需要动态设置“is.class”也许不是你的问题,但是你可以通过
表(sapply(iris,function(a)class(a)[1]))
[1]
是一种处理返回2+的东西的技巧,比如
类(Sys.time())
)@r2evans听起来不错。下面的答案回答了。谢谢!矩阵只能包含一种类型。你最可能的意思是数据帧。
dataframe
。这样你就可以理解术语了。@AndreElrico谢谢Andre。我将更改标记。我将使用类似于
sum的东西(sapply(df,is.integer))
当然,您需要在sapply中动态设置“is.class”部分。也许这不是您的问题,但您可以使用
表(sapply(iris,function(a)class(a)[1]))一次获取所有类型。
[1]
是一种处理返回2+,例如
类(Sys.time())
)@r2evans听起来不错。下面的答案回答了。谢谢!您可能希望%class(x)
中的
ty%而不是
class(x)==ty
更一般(在这里重复,以防读者看不到我上面的评论或正在寻找关键字。)如果您有任何多类列,例如
POSIXct
tbl_df
,这将不起作用,您需要Moody_mudscapper提供的
%in%
技巧。您可能希望
ty%in%class(x)
而不是
class(x)==ty
更通用(在这里重复,以防读者看不到我上面的评论或正在寻找关键词。)如果你有任何多类专栏,如
POSIXct
tbl_df
,这将不起作用,你将需要Moody_Mudskipper提供的
%in%
技巧。