R:在继承 data.frame 的 S4 对象上应用 terms.formula

标签 r inheritance s4

我正在尝试创建一个从数据框继承的新类:

> setClass('new.frame',
    representation(colour='character'),
    contains = 'data.frame')

这是该类的一个实例,用于测试:
> test_data = data.frame(cbind(runif(5), runif(5)))
> names(test_data) = c('X', 'Y')
> test_frame = new('new.frame', test_data, colour='red')

只是为了确保它看起来没问题...
> data.frame
Object of class "new.frame"
          X         Y
1 0.8766306 0.4741213
2 0.1221508 0.5117665
3 0.4838761 0.4973627
4 0.7858294 0.4064749
5 0.5147703 0.9135304
Slot "colour":
[1] "red"

...并确保继承有效
> is.data.frame(test_frame)
[1] TRUE
> getClass(class(test_frame))
Class "new.frame" [in ".GlobalEnv"]

Slots:

Name:                .Data              colour               names
Class:                list           character           character

Name:            row.names            .S3Class
Class: data.frameRowLabels           character

Extends: 
Class "data.frame", directly
Class "list", by class "data.frame", distance 2
Class "oldClass", by class "data.frame", distance 2
Class "vector", by class "data.frame", distance 3

这是我在尝试利用作为数据框的属性时遇到的问题:
> terms.formula(Y ~ X, data = test_frame)
Error in terms.formula(Y ~ X, data = test_frame) : 
  'data' argument is of the wrong type

我可能错过了一些愚蠢的事情。如果是这样,在此先感谢您指出。

如果我对这里的问题是正确的,那么无论如何我可以让 terms.formula 认识到我给它一个 data.frame 的事实吗?

最佳答案

debug(terms.formula)然后运行 ​​terms.formula(Y ~ X, data = test_frame)表明您的代码在引用代码块的第 3 行和第 4 行失败:

if (!is.null(data) && !is.environment(data) && !is.data.frame(data)) 
    data <- as.data.frame(data, optional = TRUE)
terms <- .Internal(terms.formula(x, specials, data, keep.order, 
    allowDotAsName))

问题一定是对 .Internal(terms.formula()) 的调用期待一个“普通的旧”data.frame , 而是被传递一个类 new.frame 的对象.
作为一种解决方法,为什么不直接通过 terms.formula()它期望的对象类型(一个朴素的data.frame)?

这是一种简单的方法:
terms.formula(Y ~ X, data = unclass(test_frame))
# Y ~ X
# attr(,"variables")
# list(Y, X)
# attr(,"factors")
#   X
# Y 0
# X 1
# attr(,"term.labels")
# [1] "X"
# attr(,"order")
# [1] 1
# attr(,"intercept")
# [1] 1
# attr(,"response")
# [1] 1
# attr(,".Environment")
# <environment: R_GlobalEnv>

关于R:在继承 data.frame 的 S4 对象上应用 terms.formula,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149517/

相关文章:

php - json_decode 无法读取以 json 格式存储数据的文本文件

C++ "Rules"关键字包含在头文件与源/实现文件中

r - 如何使一个 S4 类从另一个 S4 类正确继承?

r - R中的method_missing等价物

r - 对于数据框中的多列,在 R 中从宽变长

r - 增加子文档的标题级别

r - 在 R 中使用蒙特卡罗模拟的风险值(value)(极值理论)

java - 类型转换泛型

generics - TypeScript 中静态方法的抽象方法版本

r - 如何定义S4方法来取对象的反面?