user3324278
user3324278

Reputation: 21

Can I prevent arguments from being passed via NextMethod in R?

I have a subclass of data.frame that needs an extra argument when subsetting. NextMethod() passes extra arguments along, which generates an error because the next method recognizes neither the argument itself, nor the 'dots' arguments.

Example:

class(Theoph) <- c('special','data.frame')
`[.special` <- function(x, i, j, drop, k, ...){
   y <- NextMethod()
   attr(y, 'k') <- k
   y
}

Theoph[1:5,k='head']

Result:

Error in `[.data.frame`(Theoph, 1:5, k = "head") : 
unused argument (k = k)

Can I make 'k' invisible downstream? I've tried removing it, defining as NULL, passing only arguments of interest, writing a wrapper. The subset operator [ is a particularly difficult generic because of some non-default argument matching rules.

Upvotes: 2

Views: 296

Answers (1)

hadley
hadley

Reputation: 103898

Since in this case you know what the next method is, why not just call it?

class(Theoph) <- c('special','data.frame')

`[.special` <- function(x, i, j, drop = TRUE, k, ...) {
  y <- `[.data.frame`(x, i, j, drop = drop)
  attr(y, 'k') <- k
  y
}

Theoph[1:5, k = 'head']

However, I would be cautious about this sort of approach since [ is a rather special function, and I don't think it actually includes ... in its argument list. (It looks like it does in the docs, but I think this is a simplification and it's not using the standard ... object)

Upvotes: 2

Related Questions