如何在R中定义新的类方法?

如何在R中定义新的类方法?,r,R,定义一个新函数是很简单的-例如,myfunct对于简单的情况,您可以这样做 f = function(x, newmethod = 2 * x) { list(x = x, newmethod = newmethod) } obj = f(3) obj$newmethod 对于简单的情况,您可以这样做 f = function(x, newmethod = 2 * x) { list(x = x, newmethod = newmethod) } obj = f(3)

定义一个新函数是很简单的-例如,
myfunct对于简单的情况,您可以这样做

f = function(x, newmethod = 2 * x) {
    list(x = x, newmethod = newmethod)
}

obj = f(3)

obj$newmethod

对于简单的情况,您可以这样做

f = function(x, newmethod = 2 * x) {
    list(x = x, newmethod = newmethod)
}

obj = f(3)

obj$newmethod
1)参考类RSelenium使用参考类,这是一个包含在R中的OO系统。RSelenium定义了3个参考类:
errorHandler
remoteDriver
webElement

# define class, properties/fields and methods
Obj <- setRefClass("Obj", 
  fields = list(obj = "numeric"),
  methods = list(
    newmethod = function() 2 * obj
  )
)

# instantiate an object of class Obj
obj1 <- Obj$new(obj = 3)

# run newmethod
obj1$newmethod()
## [1] 6
根据问题中的示例,我们可以使用下面的代码。这里的代码中没有使用包

有关引用类的更多信息,请参见
?referenceclass

# define class, properties/fields and methods
Obj <- setRefClass("Obj", 
  fields = list(obj = "numeric"),
  methods = list(
    newmethod = function() 2 * obj
  )
)

# instantiate an object of class Obj
obj1 <- Obj$new(obj = 3)

# run newmethod
obj1$newmethod()
## [1] 6
#定义类、属性/字段和方法
Obj1)参考类RSelenium使用参考类,这是一个包含在R中的OO系统。RSelenium定义了3个参考类:
errorHandler
remoteDriver
webElement

# define class, properties/fields and methods
Obj <- setRefClass("Obj", 
  fields = list(obj = "numeric"),
  methods = list(
    newmethod = function() 2 * obj
  )
)

# instantiate an object of class Obj
obj1 <- Obj$new(obj = 3)

# run newmethod
obj1$newmethod()
## [1] 6
根据问题中的示例,我们可以使用下面的代码。这里的代码中没有使用包

有关引用类的更多信息,请参见
?referenceclass

# define class, properties/fields and methods
Obj <- setRefClass("Obj", 
  fields = list(obj = "numeric"),
  methods = list(
    newmethod = function() 2 * obj
  )
)

# instantiate an object of class Obj
obj1 <- Obj$new(obj = 3)

# run newmethod
obj1$newmethod()
## [1] 6
#定义类、属性/字段和方法

Obj?结局如何goal@JorgeLopez这个问题很公平。TBH,我只是想了解类方法构造,因为我经常使用它(在RSelenium中),但我不理解它。我已经读了一些,但(到目前为止)还没有找到明确的参考?结局如何goal@JorgeLopez这个问题很公平。TBH,我只是想了解类方法构造,因为我经常使用它(在RSelenium中),但我不理解它。我已经读了一些,但是(到目前为止)还没有找到太多关于它的明确的参考。代码运行,但它在做什么?我们是不是在这里通过定义obj=f(3)
而不是简单地定义obj=3来作弊?很抱歉,她创建了一个依赖于参数x的函数。他创建了一个包含两个元素(元素x和元素newMethod)的列表对象。因此,通过应用f(3),他创建了一个列表对象,其中第一个元素等于3,第二个元素等于6(第一个元素的名称是x,第二个元素的名称是newmethod),非常感谢。代码运行,但它在做什么?我们是不是在这里通过定义obj=f(3)
而不是简单地定义obj=3来作弊?很抱歉,她创建了一个依赖于参数x的函数。他创建了一个包含两个元素(元素x和元素newMethod)的列表对象。因此,通过应用f(3),他创建了一个列表对象,其中第一个元素等于3,第二个元素等于6(第一个元素的名称是x,第二个元素的名称是newmethod)
# constructor 
obj <- function(x) structure(x, class = "obj")

# method
newmethod <- function(x, ...) UseMethod("newmethod")
newmethod.obj <- function(x, ...) 2 * x

# create object obj3 of class "obj" and apply newmethod to it.
obj3 <- obj(3)
newmethod(obj3)
## [1] 6