2

I am implementing a replacement for the subset operator in an S3 class. I followed the advice on

How to define the subset operators for a S4 class?

However I am having a special problem. How do I distinguish in R code if someone wrote x[i] or x[i,]. In both cases, the variable j just comes back missing.

setOldClass("myclass")

'[.myclass' <- function(x, i, j, ..., drop=TRUE) {
    print(missing(j))
    return(invisible(NULL))
}

And as a result I get:

x <- structure(list(), class="myclass")
> x[i]
[1] TRUE
> x[i,]
[1] TRUE
> x[i,j]
[1] FALSE

I don't see a way on how to distinguish between the two. I assume the internal C code does it by looking at the length of the argument pairlist, but is there a way to do the same in native R?

Thanks!

Community
  • 1
  • 1
Holger Hoefling
  • 388
  • 3
  • 13

1 Answers1

0

From alexis_laz's comment:

See, perhaps, how [.data.frame handles arguments and nargs()

Inside the function call nargs() to see how many arguments were supplied, including missing ones.

> myfunc = function(i, j, ...) {
+   nargs()
+ }
> 
> myfunc()
[1] 0
> myfunc(, )
[1] 2
> myfunc(, , )
[1] 3
> myfunc(1)
[1] 1
> myfunc(1, )
[1] 2
> myfunc(, 1)
[1] 2
> myfunc(1, 1)
[1] 2

This should be enough to help you figure out which arguments were passed in the same fashion as [.data.frame.

CoderGuy123
  • 6,219
  • 5
  • 59
  • 89