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

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Thu Dec 2 21:57:11 CET 2021


Hi everyone,

Suppose I've got a class 'foo' that's a matrix tagged with a vector of
length() == nrow(foo):

foo <- function(x, ...) UseMethod('foo')
foo.matrix <- function(x, y, ...) {
	stopifnot(
		!is.recursive(y),
		length(y) == nrow(x),
		length(list(...)) == 0
	)
	structure(x, class = 'foo', foo = y)
}

The invariant that the vector follows the rows of the matrix must be
maintained, so I write a [.foo method:

`[.foo` <- function(x, i, j, ..., drop = TRUE) {
	ret <- NextMethod() # could drop dimensions
	if (is.matrix(ret)) foo(
		ret,
		unname(setNames(attr(x, 'foo'), dimnames(x)[[1]])[i])
	)
	else ret
}

Note the acrobatics required to handle indexing objects of class foo by
the dimnames of the matrix. If I used foo(attr(x,'foo')[i]) instead,
indexing by dimnames would result in the correct subset of the matrix
tagged with a vector of NAs.

Now I would like to implement sub-assignment. I would like to access
the correct subset of the 'foo' vector (for example, if value is also
of class foo, I would like to check if the 'foo' attributes match
between value and x), but I don't want to copy&paste the code or create
a separate method, so I call `[.foo` instead:

`[<-.foo` <- function(x, i, j, ..., value) {
	xsub <- x[i,j]
	# safety checks on attr(xsub, 'foo')
	NextMethod()
}

...except this doesn't quite work:

x <- foo(volcano, 1:nrow(volcano))
x[] <- 1
# Error in NextMethod() : argument "i" is missing, with no default
traceback()
# 5: NextMethod() at foo.R#15
# 4: `[.foo`(x, i, j) at foo.R#24
# 3: x[i, j] at foo.R#24
# 2: `[<-.foo`(`*tmp*`, , value = 1)
# 1: `[<-`(`*tmp*`, , value = 1)

Why can I forward missing i,j to built-in `[`

-- 
Best regards,
Ivan



More information about the R-help mailing list