【问题标题】:Get list of datatypes with S3 generic function使用 S3 通用函数获取数据类型列表
【发布时间】:2015-05-22 07:08:27
【问题描述】:

我尝试编写一个函数,我可以在其中输入任意数量的对象并获取该对象的数据类型列表。这是学习 S3 泛型的个人任务。

到目前为止我所做的是:

myTypes <- function(x, ...) {
  dots <- list(...)
  return (as.list(apply(dots, 1, myType)))
}

myType <- function(x){
  UseMethod("myType")
}

myType.numeric <- function(x){
  if(is.numeric(x)) "Type: numberic"
}

myType.data.frame <- function(x){
  if(is.data.frame(x)) "Type: dataframe"
}

发生错误,例如当我打电话时

x <- 1
y <- 3

myTypes(x,y)

我总是收到错误:"Error in apply(dots, 1, myType) : dim(X) must have a positive length",我不确定出了什么问题。有人可以在这里帮助我吗?由于我对 R 完全陌生,所以我可能做错了什么。

【问题讨论】:

    标签: r generics types r-s3


    【解决方案1】:

    apply 的第一个参数必须是类似矩阵的对象(即矩阵、数组或 data.frame)。否则你会得到这个错误:

    apply(1, 1, mean)
    #Error in apply(1, 1, mean) : dim(X) must have a positive length
    

    您将一个列表传递给apply,这不起作用,因为您告诉apply 沿第一个维度应用该函数,而列表没有维度。

    您可能想使用lapply 而不是apply

    myTypes <- function( ...) {
      dots <- list(...)
      lapply(dots, myType)
    }
    
    x <- 1
    y <- 3
    
    myTypes(x,y)
    #[[1]]
    #[1] "Type: numberic"
    #
    #[[2]]
    #[1] "Type: numberic"
    

    当然,简单地返回类似乎更有用:

    myTypes <- function(...) {
      dots <- list(...)
      lapply(dots, class)
    }
    
    myTypes(x,y)
    #[[1]]
    #[1] "numeric"
    #
    #[[2]]
    #[1] "numeric"
    

    顺便说一句,如果使用 S3 方法分派,则不必测试方法内部的类,因为只有当对象具有相应的类时才会分派方法。

    【讨论】:

    • 感谢您的帮助和良好的解释!这对我帮助很大!
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2022-10-31
    • 2018-05-24
    • 2021-05-11
    相关资源
    最近更新 更多