Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subsetting S7 objects #517

Closed
lgatto opened this issue Dec 26, 2024 · 3 comments
Closed

Subsetting S7 objects #517

lgatto opened this issue Dec 26, 2024 · 3 comments

Comments

@lgatto
Copy link
Contributor

lgatto commented Dec 26, 2024

I hope I haven't missed anything obvious in the documentation, but how should I implement [ for an S7 object?

I see that there's a check_subsettable() that says that S7 objects are not subsettable and working with trying to work with

method(`[`, ....)

complains about not being able to convert signature to a valid class.

@lgatto
Copy link
Contributor Author

lgatto commented Dec 26, 2024

So here's an example of what I want to do. This works in a script:

library(S7)

Klass <- new_class("Klass",
  properties = list(
    data1 = class_list,
    data2 = class_data.frame))

`[.Klass` <- function(x, i)
    Klass(data1 = x@data1[i],
           data2 = x@data2[i, ])
> k <- Klass(data1 = as.list(1:3),
+ data2 = data.frame(x = 1:3, y = letters[1:3]))
> k
<Klass>
 @ data1:List of 3
 .. $ : int 1
 .. $ : int 2
 .. $ : int 3
 @ data2:'data.frame':	3 obs. of  2 variables:
 .. $ x: int  1 2 3
 .. $ y: chr  "a" "b" "c"
> k[1:2]
<Klass>
 @ data1:List of 2
 .. $ : int 1
 .. $ : int 2
 @ data2:'data.frame':	2 obs. of  2 variables:
 .. $ x: int  1 2
 .. $ y: chr  "a" "b"

But if I put the same in a package, it fails with Error in check_subsettable(x) : S7 objects are not subsettable..

Back to my script, the S7 syntax

method(`[`, list(Klass, class_numeric)) <-
    function(x, i)
        Klass(data1 = x@data1[i],
              data2 = x@data2[i, ])

don't work, throwing

Error: Can't convert `signature` to a valid class. Class specification must be an S7 class object, the result of `new_S3_class()`, an S4 class object, or a base class, not a <list>.

@mjskay
Copy link

mjskay commented Dec 29, 2024

I think [ only dispatches on the first argument, so you need method(`[`, Klass) <- ...

The error Class specification must be an S7 class object, the result of `new_S3_class()`, an S4 class object, or a base class, not a <list> hints at this obliquely, since single-dispatch methods just take the class, not a list of classes.

@lgatto
Copy link
Contributor Author

lgatto commented Dec 29, 2024

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants