【问题标题】:Can mode(), storage.mode() or typeof() return "S3"? Why or why not? (They can return "S4"!)mode()、storage.mode() 或 typeof() 可以返回“S3”吗?为什么或者为什么不? (他们可以返回“S4”!)
【发布时间】:2019-09-16 07:32:56
【问题描述】:

S4 可以作为mode()storage.mode()typeof() 的任一结果,如下所示。 那么,S3 也一样吗?为什么或为什么不?

storing <- function(x) {print(c(class(x), mode(x), storage.mode(x), typeof(x)))}

setClass("dummy", representation(x="numeric", y="numeric"))

S4DummyObject = new("dummy", x=1:20, y=rnorm(20))

storing(S4DummyObject) # "dummy" "S4"    "S4"    "S4" 

【问题讨论】:

  • typeof() 的文档似乎很清楚,可能的值包括 S4,(但只有 一些 S4 对象)而不是 S3。原因可能是 S3 对象没有以任何特殊方式在内部存储,与向量或列表之类的东西分开。

标签: r class types storage mode


【解决方案1】:

至于typeof()、“mode(x)storage.mode(x)typeof(x)”不要返回S3,因为:
typeof() 的文档似乎很清楚,可能的值包括S4,(但只有一些S4 对象)而不是S3。 (正如乔兰所说)。
(原因可能是 S3 对象没有以任何特殊方式在内部存储,与向量或列表之类的东西分开)。

至于“mode(x),storage.mode(x)”,可以通过观察将我们得到S4的情况复制为“mode(x),storage.mode(x)”的返回值会发生什么。

new_s3_lst <- function(x, ..., class) {
     stopifnot(is.list(x))
     stopifnot(is.character(class))
     structure(x, ..., class = class)
 } 

new_s3_scalar <- function(..., class) { new_s3_lst(list(...), class = class) }

S3DummyObject = new_s3_scalar(class="dummy")
class(S3DummyObject) # "dummy"
storing <- function(x) {print(c(class(x), mode(x), storage.mode(x), typeof(x)))}
storing(S3DummyObject) # "dummy" "list"  "list"  "list"

所以,可以分别得到dummyS4S4S4作为class(x)mode(x)storage.mode(x)typeof(x)的返回值;但是对于S3,最多可以从class(x)mode(x)storage.mode(x)typeof(x)分别得到dummylistlistlist

【讨论】:

  • S3获取不到,没关系。但是,我认为一个 S3 对象的返回值可以获得超过 list 的值。因此,您的“至多”似乎是多余的。
猜你喜欢
  • 2022-11-02
  • 1970-01-01
  • 2018-10-05
  • 2018-07-08
  • 2011-05-22
  • 1970-01-01
  • 2012-05-21
  • 2011-02-17
相关资源
最近更新 更多