R 中的对象可以有多个类吗?

qed*_*qed 5 oop r

假设我有一个这样的函数:

myf = function(x) {
res = dostuff(x)
res # this is a data.frame
}
Run Code Online (Sandbox Code Playgroud)

我想做一些特别的事情res,例如,我想制作一些通用函数,例如print.myf, summary.myf, ... ,这样我就可以继续给它一个类:

myf = function(x) {
res = dostuff(x)
class(res) = 'myf'
res
}
Run Code Online (Sandbox Code Playgroud)

但是这样我就不能再将它用作 data.frame 了。

A5C*_*2T1 3

这是一个带有 的示例rle。该rle函数创建了一个list,但它没有类list,因此类似的方法as.data.frame无法“开箱即用”。因此,我更改了最后一行以添加"list"为其中一个类。

x <- c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3)

rle2 <- function (x)
{
  if (!is.vector(x) && !is.list(x))
    stop("'x' must be an atomic vector")
  n <- length(x)
  if (n == 0L)
    return(structure(list(lengths = integer(), values = x),
                     class = "rle"))
  y <- x[-1L] != x[-n]
  i <- c(which(y | is.na(y)), n)

  ## THE FOLLOWING IS FROM THE BASE RLE. NOTICE ONLY ONE CLASS...
  # structure(list(lengths = diff(c(0L, i)), values = x[i]), 
  #  class = "rle")

  structure(list(lengths = diff(c(0L, i)), values = x[i]),
            class = c("rle", "list"))
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我只是更改了class. 其余功能相同。

rle(x)
# Run Length Encoding
#   lengths: int [1:3] 4 3 7
#   values : num [1:3] 1 2 3
data.frame(rle(x))
# Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
#   cannot coerce class ""rle"" to a data.frame
rle2(x)
# Run Length Encoding
#   lengths: int [1:3] 4 3 7
#   values : num [1:3] 1 2 3
data.frame(rle2(x))
#   lengths values
# 1       4      1
# 2       3      2
# 3       7      3
Run Code Online (Sandbox Code Playgroud)

当然,如果我们知道这一点,如果我们知道存在一个方法,我们也可以显式指定我们的方法:

as.data.frame.list(rle(x))
#   lengths values
# 1       4      1
# 2       3      2
# 3       7      3
Run Code Online (Sandbox Code Playgroud)