RC-class structure in r

307 Views Asked by At

I am trying to understand RC classes in R (unsuccessfully). I have a simple function which returns an object of class Example. I would now like to use this function in an RC class, where I implement some methods for it. As of now I don't understand how to structure my code (e.g if the function is one r-script and the RC class I am trying to create another or if they should be in the same r-script), and how to correctly access the objects of class Example in order to get the desired output.

Below is an example:

example <- function(x, y){
  tripplex <- x*3
  doubbley <- y*2
  xy_sum <- x+y
  
  Example <- list(trippled.x = tripplex, doubbled.y = doubbley, sum =xy_sum)
  class(Example) <- "Example"
  Example
}

### I now want to use this function in an RC class and write some methods for it. ###
testClass <- setRefClass("testClass",
                         fields=list(x = "numeric",y = "numeric"),
                         methods = list(
                           initialize = function(){
                             # I don't know what to initialize it as.
                           },
                           show = function() {
                             cat(paste0("Call:\n", "x=", .self$x ,"\n", "y=", .self$y))
                             # This doesn't print proper x,y values.
                             }))

My idea is that I want something like this output:

>object <- example(5, 10)
>print(object)
Call: 
x=5
y=10
>
>object$trippled.x
15

Regards

1

There are 1 best solutions below

4
Allan Cameron On

Are you looking for something like this?

testClass <- setRefClass("testClass",
               fields   = list(
                  x = "numeric", 
                  y = "numeric"
               ),
                methods = list(

                  initialize = function(x, y) {
                    .self$x = x
                    .self$y = y
                  },

                  tripled_x  = function() {
                    return(3 * .self$x)
                  },
                  
                  show       = function() {
                    cat(paste0("Call:\n", "x=", .self$x ,"\n", "y=", .self$y))

                  }))

 object <- testClass(5, 10)
 print(object)
#> Call:
#> x=5
#> y=10
 object$tripled_x()
#> [1] 15

Created on 2021-09-20 by the reprex package (v2.0.0)