R 中可以有自己的类的对象吗?
我是 R 新手,我想知道是否可以创建自己的类的对象。当我读到“help(class)”时,似乎没有像Java中那样的类是可能的。我的意思是我想要一个带有方法、私有变量和构造函数的类。例如,它可能如下所示:
className <- class {
# private variables
var1 <- "standardvalue"
var2 <- TRUE
# Constructor
constructor (v1, v2) {
var1 <- v1
var2 <- v2
}
# Method 1
function sum() {
var1 + var2
}
# Method 2
function product() {
var1 * var2
}
}
在我的主程序中,我想创建此类的对象并调用它的函数。例如这样:
# Create Object
numbers <- className(10,7)
# Call functions of the Object
numbers -> sum() # Should give "17"
numbers -> product() # Should give "70"
这样的事情可能吗?到目前为止我还没有找到任何例子。
感谢您的帮助。
I'm a R-newbie, and I was wondering if it is possible to create objects of own classes. When I read the "help(class)" it did not seem that classes like in Java are possible. I mean I want to have a class with methods, private variables and a constructor. For example it could look like this:
className <- class {
# private variables
var1 <- "standardvalue"
var2 <- TRUE
# Constructor
constructor (v1, v2) {
var1 <- v1
var2 <- v2
}
# Method 1
function sum() {
var1 + var2
}
# Method 2
function product() {
var1 * var2
}
}
In my main programm I want to create an Object of this Class and call it's functions. For example like this:
# Create Object
numbers <- className(10,7)
# Call functions of the Object
numbers -> sum() # Should give "17"
numbers -> product() # Should give "70"
Is something like this possible? So far I did not fine any example.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在基础 R 中有(至少)三个 OO 系统可供选择:
以及通过 CRAN 包(例如 proto)提供的其他类似 OO 的框架。
请对 S3、S4、ReferenceClasses、OO 等进行一些谷歌搜索,可能从 rseek.org 开始。所有 R 编程书籍也涵盖了这一点;我最喜欢的是 Chambers (2008) 题为“数据分析软件”的书。
Yes, there are (at least) three OO systems to choose from in base R:
plus additional OO-like frameworks contributed via CRAN packages such as proto.
Please do some googling for S3, S4, ReferenceClasses, OO, ..., possibly starting at rseek.org. All R programming books cover this too; my favourite is Chambers (2008) book titled "Software for Data Analysis".
如果您来自
java
,因此习惯于private
和public
属性和方法,我建议您使用R6< /代码> 包。请参阅此链接。从文档中获取的 person 类的一个简单示例如下:
以下是创建此类实例的方法:
请注意,与
java
方法不同的是,使用$
运算符调用在对象之后。If you come from
java
and therefore are used toprivate
andpublic
attributes and methods I'd advise you to use theR6
package. See this link. A trivial example of a person class taken from the documentation is this:Here's how you can create an instance of this class:
Note that unlike
java
methods are invoked using the$
operator after the object.