[R] Forwarding missing arguments to the `[` method

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Dec 8 14:52:00 CET 2021


Got some progress on this, but still not sure how to continue. First, a
much more simple script reproducing the behaviour that confuses me:

foo <- function(x, ...) structure(x, class = 'foo')
`[.foo` <- function(x, i, ..., drop = TRUE) {
	print(sys.call())
	print(match.call())
	foo(NextMethod()) # x[] should return an object of class foo
}
`[<-.foo` <- function(x, i, ..., value) {
	print(sys.call())
	print(match.call())
	x[i, ..., drop = FALSE]
	# imagine that we need to perform some checks on the
	# subset of x that we're about to replace
	NextMethod()
}

x <- foo(42)
x[]      # this works
x[] <- 1 # this doesn't

Now, the crucial difference between the x[] and x[] <- 1 calls is that
in the former case, the `i` argument isn't even specified:

x[]
# `[.foo`(x, )
# `[.foo`(x = x)
# [1] 42
# attr(,"class")
# [1] "foo"

While in the latter case, `i` is specified in the x[] call (but
missing):

x[] <- 1
# `[<-.foo`(`*tmp*`, , value = 1)
# `[<-.foo`(x = `*tmp*`, value = 1)
# x[i, ..., drop = FALSE]
# `[.foo`(x = x, i = i, drop = FALSE)
Error in NextMethod() : argument "i" is missing, with no default

What's the best way to forward the arguments from [<-.class methods to
the [.class methods in order to handle cases like x[] properly?

-- 
Best regards,
Ivan



More information about the R-help mailing list