Home > Back-end >  How to use replace function for setAs() in R?
How to use replace function for setAs() in R?

Time:09-26

I am trying to define a coerce method in R including a replace function. Unfortunately, neither the documentation of setAs() nor further discussions on the internet clarify the way how to use the parameter replace in this function.

My target is to get a coerce method working the same in these two commands:

obj <- as(obj, "to-class")
as(obj) <- "to-class"

For instance, I set a method to coerce the class "table" to "data.frame", including a function for a replacement method:

setAs(from = "table", to = "data.frame",
    def = function(from) {
      return(as.data.frame(from))
    },
    replace = function(from, value) {
      from <- as(from, value)
      return(from)
    })

Now the method in action

data(Titanic)
x <- Titanic

# two coerce alternatives
y <- as(x, "data.frame")
as(x) <- "data.frame"

While the first works perfect, the second retrieves me an error:

Error in .identC(.class1(value), Class) :
argument "Class" is missing, with no default

Am I doing something wrong or maybe expecting too much from setAs()?

CodePudding user response:

replace doesn't do what you think it does. It exists to allow direct assignment of an uncoerced object into a coerced version. The second argument is not supposed to be the class name, but an uncoerced object.

To take your table / data.frame coercion, we could write.

setAs(from = "table", to = "data.frame",
      def = function(from) {
        return(as.data.frame(from))
      },
      replace = function(from, value) {
        from <- as.data.frame(value)
        return(from)
      })

So if we have a table called x

x <- table(iris$Species)
x

#> setosa versicolor  virginica 
#>     50         50         50 

We can assign a different table's data and coerce to a data.frame in one go by doing:

as(x, "data.frame") <- table(mtcars$cyl)
x
#>   Var1 Freq
#> 1    4   11
#> 2    6    7
#> 3    8   14

Effectively, it's the same as writing

x <- as(table(mtcars$cyl), "data.frame")

and therefore of limited utility, which is perhaps why the documentation is scant.

CodePudding user response:

as requires object and class, so:

as(x, "data.frame") <- x

CodePudding user response:

While I still don't have any clue about what is the parameter replace in setAs() good for, I solved the issue defining a method for as()<-:

# Defining 'as()'
setAs(from = "table", to = "data.frame",
    def = function(from) {
      return(as.data.frame(from))
    })

# Defining 'as()<-'
setReplaceMethod("as", signature(object = "table", Class = "missing",
        value = "character"), 
    function(object, Class, value) {
      object <- as(object, value)
      return(object)
    })

The nice thing in this solution, the replace method will apply for any coercion defined with from = "table"

  • Related