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

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Fri Dec 3 07:52:09 CET 2021


On Thu, 02 Dec 2021 13:41:52 -0800
Jeff Newmiller <jdnewmil using dcn.davis.ca.us> wrote:

> I think you need a reprex... I don't think your claim is correct as
> stated.

Sorry, let me try again. The following "works" for me in the sense of
throwing the same error on R 3.3 and R-devel:

foo <- function(x, ...) UseMethod('foo')

# foo is a matrix tagged with a vector of length() == nrow(foo)
foo.matrix <- function(x, y, ...) {
	stopifnot(
		!is.recursive(y),
		length(y) == nrow(x),
		length(list(...)) == 0
	)
	structure(x, class = 'foo', foo = y)
}

# the vector must be subsetted at the same time as x
`[.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
}

`[<-.foo` <- function(x, i, j, ..., value) {
	xsub <- x[i, j, drop = FALSE]
	# TODO: some checks on xsub
	NextMethod()
}

x <- foo(volcano, 1:nrow(volcano))
invisible(x[]) # doesn't stop despite missing i
x[] <- 1       # fails in `[.foo` with "i missing"
# Error in NextMethod() : argument "i" is missing, with no default
traceback()
# 9: NextMethod() at foo.R#15
# 8: `[.foo`(x, i, j, drop = FALSE) at foo.R#24
# 7: x[i, j, drop = FALSE] at foo.R#24
# 6: `[<-.foo`(`*tmp*`, , value = 1) at foo.R#30
# 5: `[<-`(`*tmp*`, , value = 1) at foo.R#30
# 4: eval(ei, envir)
# 3: eval(ei, envir)
# 2: withVisible(eval(ei, envir))
# 1: source("foo.R", echo = TRUE)

Or did you mean some other claim?

-- 
Best regards,
Ivan



More information about the R-help mailing list