RobinHankin / disordR

https://robinhankin.github.io/disordR/
1 stars 0 forks source link

question #7

Closed RobinHankin closed 3 years ago

RobinHankin commented 3 years ago

I have a new S4 class "foo" and want to use it to extract elements from a vector. But see the following:

rstudio % R --quiet --vanilla
> R.Version()$version.string
[1] "R version 4.1.0 (2021-05-18)"
> setClass("foo",slots=c(x="vector"))
> (a <- new("foo",x=1:3))
An object of class "foo"
Slot "x":
[1] 1 2 3

> setMethod("[",signature=c(x="ANY",i="foo"),function(x,i){"hello"})
> letters[a]
Error in letters[a] : invalid subscript type 'S4'
> 

Desired behaviour is for "letters[a]" on the last line to dispatch to the "hello" function, but I get this error instead. What is wrong with my understanding?

RobinHankin commented 3 years ago

In the Matrix package it says:

##--- Something else:  Allow    v[ <sparseVector> ] -- exactly similarly:
if(FALSE) { ## R_FIXME: Not working, as internal "[" only dispatches on 1st argument
setMethod("[", signature(x = "atomicVector", i = "lsparseVector"),
      function (x, i, j, ..., drop) x[sort.int(i@i[i@x])])
setMethod("[", signature(x = "atomicVector", i = "nsparseVector"),
      function (x, i, j, ..., drop) x[sort.int(i@i)])
}
RobinHankin commented 3 years ago

so that's what is wrong: R only dispatches on the first argument. But that is not a problem here because I only need extraction methods where both x and i are disord objects.