简体   繁体   中英

composition of R6 objects in R

I am trying to learn OOP in R with R6 objects. I have a problem that might seem easy, but cannot figure out how to do it. Any help is appreciated

Suppose I have a class of an object, say "Student" that has some numerical characteristics eg grades.* I would like to have a compostion of such objects, say "Classroom" and be able to perform calculations on a whole matrix of "Student" characteristics eg multiply all "Student" grades by some weigths.

Student <- R6Class(
  "Student",
  public = list(
    grades = NULL, 
    initialize = function(grades) {
      if(!missing(grades)) {self$grades <- grades}
    },
    mult.by.vector = function(v){
      newgrades <- self$grades*v
      return(Student$new(grades=newgrades)
      )
    }
  )
)

John<-Student$new(c(4,5,5))
John$mult.by.vector(c(1.1,1.2,0.9))

Ann<-Student$new(c(5,4,4))

Now, I would like to have a composition of Ann and John and be able to perfrom mult.by.vector on both at the same time.

Should I use inheritance? Or just some list?

*In fact, my application is very different, but the problem is more or less the same.

f

I know it's been a while since you posted this question. But to me, who is trying to get a bit more insights into R6 classes, it was a good opportunity to exercise using your problem and to poke an old friend on StackOverflow:)

My proposed solution requires:

  1. making a list of students a list ( studs in my code) and not separate entries, like your Ann or John ,
  2. initiating each student within a list entry, and
  3. applying the lapply to perform the same operation (multiplication of the grades by a vector of factors).
studs <- vector("list", 2)
studs[[1]] <-Student$new(c(4,5,5))
studs[[2]] <-Student$new(c(5,4,4))

lapply(1:2, 
   function(id){
      studs[[id]]$mult.by.vector(c(1.1,1.2, 0.9))
   }
)

I would also consider extending your class Student by some form of identification, that is, a name or student ID.

What do you say?

Greetings from Melbourne,

Tomasz:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM