S4 class is not a subset

I am trying to write a subset method for an S4 class. I get the error this S4 class is not subsettable

no matter what I try.

Here's a minimal example:

setClass(Class = "A", representation = representation(ID = "character"))
setClass(Class = "B", representation = representation(IDnos = "list"))

a1 <- new(Class = "A", ID = "id1")
a2 <- new(Class = "A", ID = "id2")

B1 <- new(Class = "B", IDnos = c(a1, a2))

      

When I type:

B1@IDnos[[1]]

      

I get what I want:

> An object of class "A"
> Slot "ID":
> [1] "id1"

      

But I want to get this just by writing something like:, B1[1]

or if notB1[[1]]

From THIS post, I got some idea and tried to emulate what the author wrote. But it didn't work in my case:

setMethod("[", c("B", "integer", "missing", "ANY"),
          function(x, i, j, ..., drop=TRUE)
          {
            x@IDnos[[i]]
            # initialize(x, IDnos=x@IDnos[[i]])    # This did not work either
          })
B1[1]

> Error in B1[1] : object of type 'S4' is not subsettable

      

The following code doesn't work:

setMethod("[[", c("B", "integer", "missing"),
          function(x, i, j, ...)
          {
            x@IDnos[[i]]
          })
B1[[1]]

> Error in B1[[1]] : this S4 class is not subsettable

      

Any ideas?

+3


source to share


1 answer


I think your problem is your signature is too strong. You need an "integer" class. Default

class(1)
# [1] "numeric"

      

So this is not a true "integer" data.type. But when you actually specify an integer literal

class(1L)
# [1] "integer"

B1[1L]
# An object of class "A"
# Slot "ID":
# [1] "id1"

      



So it's better to use a more general signature

setMethod("[", c("B", "numeric", "missing", "ANY"), ... )

      

which will allow your initial attempts to work

B1[2]
# An object of class "A"
# Slot "ID":
# [1] "id2"

      

+6


source







All Articles