简体   繁体   English

R:使用特定构造函数为“data.frame”创建新的Class后代

[英]R: Create new Class offspring to “data.frame” with specific constructor

I am trying to create a new class in R for the first time and I have a hard time. 我想第一次在R中创建一个新类,我很难过。

Question

Can you please show me how one could create a class that inherits from the class "data.frame" but can only contain 3 columns named col1 , col2 and col3 . 你能否告诉我如何创建一个继承自“data.frame”类的类,但只能包含名为col1col2col3 3列。 All columns must be "numeric" and the relation col1 + col2 = col3 must hold true. 所有列必须为“数字”,并且关系col1 + col2 = col3必须为true。

The user could do 用户可以这样做

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

or 要么

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

or 要么

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

to create an object of this class. 创建此类的对象。 All of the above lines would all yield to a similar output to 所有上述行都会产生类似的输出

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

What I tried 我尝试了什么

Here is all I manage to do so far. 这是我到目前为止所做的一切。

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))

I failed to 我失败了

  • inherit from "data.frame" 继承自“data.frame”
  • to force the function "calc" to apply automatically at the moment of the construction of an object of the new class. 强制函数“calc”在构造新类的对象时自动应用。

Maybe just do a S3 class: 也许只做一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM