Home > Software design >  Setter and getter methods in R programming S4 OOP
Setter and getter methods in R programming S4 OOP

Time:09-18

I am new to R programming, so this may be a basic question.

I have a class "Student" with 3 properties - name, rollnumber and score. I have set name and rollnumber while creating the object and set score to 0. There are 2 methods to set and get values to score. But setting the value using this method is not retaining in the object. It is still showing the initial score 0 even after setting that to 100 using the setter method.

This is my code -

setClass("Student", slots = list(name = "character", rollnumber="numeric", score="numeric"))
st1 <- new("Student", name="Sachin", rollnumber=24, score=0)

setGeneric("setScore", function(model, score){
  standardGeneric("setScore")
})
setGeneric("getScore", function(model){
  standardGeneric("getScore")
})

setMethod("setScore", signature("Student"), function(model, score){
  model@score <- score
})


setMethod("getScore", signature("Student"), function(model){
  paste0(model@name, "'s score is: ", model@score)
})

setScore(st1, 100)
getScore(st1)

CodePudding user response:

S4 objects are not "reference objects". If you want to change them, you need to make the change and assign the result to a new object. So change your setter to

setMethod("setScore", signature("Student"), function(model, score){
  model@score <- score
  model
})

and use it as

st1 <- setScore(st1, 100)

There are a few different schemes for reference objects. I'd recommend the R6 package rather than the one in base R. You can read about it here: https://r6.r-lib.org/articles/Introduction.html .

  • Related