R:使用特定的构造函数创建新的类后代到 "data.frame"

标签 r class inheritance

我第一次尝试在 R 中创建一个新类,但遇到了困难。

问题

你能告诉我如何创建一个继承自类“data.frame”但只能包含名为 col1 的 3 列的类吗? , col2col3 .所有列都必须是“数字”并且关系 col1 + col2 = col3必须成立。

用户可以做

ClassName(col1 = rep(10,10), col2 = 1:10)

ClassName(col1 = rep(10,10), col3 = 11:20)

ClassName(col2 = 1:10, col3 = 11:20)

创建这个类的一个对象。以上所有行都会产生与

类似的输出
data.frame(col1 = rep(10,10), col2 = 1:10, col3 = rep(10,10)+(1:10))
   col1 col2 col3
1    10    1   11
2    10    2   12
3    10    3   13
4    10    4   14
5    10    5   15
6    10    6   16
7    10    7   17
8    10    8   18
9    10    9   19
10   10   10   20

我尝试过的

到目前为止,这是我设法做的所有事情。

setClass("newClass", representation(col1="numeric",col2="numeric",col3="numeric"), contains="numeric")

calc.newClass = function(obj)
{
    if (length(obj@col1)==0)
    {
        return(new("newClass", col1=obj@col3-obj@col2, col2=obj@col2, col3=obj@col3)    )
    }
    if (length(obj@col2)==0)
    {
        return(new("newClass", col1=obj@col1, col2=obj@col3-obj@col1, col3=obj@col3)    )
    }
    if (length(obj@col3)==0)
    {
        return(new("newClass", col1=obj@col1, col2=obj@col2, col3=obj@col1+obj@col2)    )
    }

}

o = calc.newClass(new("newClass", col1=rep(10,10), col3=11:20))

我失败了

  • 继承自“data.frame”
  • 强制函数“calc”在构造新对象时自动应用 类。

最佳答案

也许只做一个 S3 类:

myclass <- function(col1, col2) {
  if (missing(col2)) { stopifnot(is.numeric(col1)); col2 <- col1*2 }
  if (missing(col1)) { stopifnot(is.numeric(col2)); col1 <- col2/2 }
  structure(data.frame(col1, col2), class = c("myclass", "data.frame"))
}
(res <- myclass(col2=1:3))
#   col1 col2
# 1  0.5    1
# 2  1.0    2
# 3  1.5    3
class(res)
# [1] "myclass"    "data.frame"

(res <- myclass(col1=1:3))
#   col1 col2
# 1    1    2
# 2    2    4
# 3    3    6

(res <- myclass(col1=letters[1:3]))
# Error: is.numeric(col1) ist nicht TRUE

(res <- myclass())
# Error in stopifnot(is.numeric(col1)) : 
#   argument "col1" is missing, with no default

关于R:使用特定的构造函数创建新的类后代到 "data.frame",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976439/

相关文章:

c++ - 在 .cpp 文件中使用类的静态成员

c++ - 从基类的 vector 访问继承的类方法

Hibernate MappingException 与 Grails 中具体非域类的继承

R:表命令中的参数必须全部具有相同的长度

r - 如何在sf R包中按组测量空间点之间的距离

r - Geom_tile 绘制时间轴数据中不存在的不连续性

javascript - 如何通过 id 和 class 获取元素

r - 使用 seq.Date 作为时间序列的 stat_bin 中的中断

c++ - 仅当它不是模板时才编译具有结构类型的同名变量

delphi - 找出Delphi ClassType是否继承自其他ClassType?