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.
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”.