使用S3泛型函数获取数据类型列表



我试着写一个函数,我可以扔进任意数量的对象,并获得该对象的数据类型列表。这是学习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完全陌生,我可能做了一些基本错误的事情。

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方法分派,则不必在方法内部测试类,因为只有当对象具有相应的类时才会分派方法。

最新更新