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

Get list of datatypes with S3 generic function

我尝试编写一个函数,我可以在其中放入任意数量的对象并获取这些对象的数据类型列表。这是学习 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"

当然好像更有用,要简单return class:

myTypes <- function(...) {
  dots <- list(...)
  lapply(dots, class)
}

myTypes(x,y)
#[[1]]
#[1] "numeric"
#
#[[2]]
#[1] "numeric"

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