【问题标题】:how to determine class of an object如何确定对象的类别
【发布时间】:2015-10-23 11:26:44
【问题描述】:

注意-相关问题没有解释为什么attr(myVar, "class") 返回NULL 而不是list(以及为什么class(myVar) 返回list)。 R中检查对象类的标准方法是什么?

如何确定一个对象是“我的自定义类”还是“我的自定义类”对象的“列表”?

foo <- function(x) {
  a=list(x=x)
  attr(a, "class") <- "myclass"
  return(a)
}

newVar = list(foo(10),foo(20))

现在我想知道newVar是什么类。

attr(newVar, "class")  # NULL, but not list!
#NULL

##however this works fine
attr(newVar[[1]], "class")
#[1] "myclass"

为什么会这样?在 R 中确定类的正确方法是什么?

【问题讨论】:

标签: r oop


【解决方案1】:

确定对象的S3类的“正确方法”是使用函数class

隐式类:

class(list(1))
#[1] "list"
class(1:5)
#[1] "integer"

显式类:

class(list(1))
class(lm(Sepal.Length ~ Sepal.Width, data = iris))
#[1] "lm"

x <- 1:5
class(x) <- "myclass"
class(x)
#[1] "myclass"

由于列表可以包含任何内容,因此您必须遍历它以找出其中的对象的类,例如,sapply(yourlist, class)

类 ID 存储为属性(名称、维度和其他一些东西也是如此),但通常您无需担心这些内部结构,因为 R 提供了访问器函数。

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2016-09-06
    • 2011-01-14
    相关资源
    最近更新 更多