gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:42:50 27 4
gpt4 key购买 nike

我第一次尝试在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com