Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is rep really a generic?

When I type the function name of a generic in to my console, I expect to see a call to UseMethod. For example, the documentation for determinant calls it a generic and I get the following output when I type it in to my console:

> determinant
function (x, logarithm = TRUE, ...) 
UseMethod("determinant")
<bytecode: 0x55fb617086b8>
<environment: namespace:base> #

The documentation for rep makes a similar claim, but my console does not give similar output:

> rep
function (x, ...)  .Primitive("rep")

And my attempts to extend rep have been unsuccessful.

This leaves me with two possibilities. Either I have a very bad understanding of R's generic functions or rep is not a generic at all. Which is it?

like image 267
J. Mini Avatar asked Mar 07 '26 22:03

J. Mini


1 Answers

In the code for the interal rep function it calls

DispatchOrEval(call, op, "rep", args, rho, &a, 0, 0)

which will only do generic dispatching if your function is "an object" which can be seen here.

Matrices in R aren't considered "objects", they are primitive types so no dispatching will take place.

is.object(matrix(1:3))
# [1] FALSE

This is a code optimization for functions that are called frequently and need to be fast.

So you will not be able to create a custom rep function for matrices using S3 generics. you'd have to shadow the base function if you want to change the behavior (which might break functions that rely on the existing behavior). Probably even better to write your own function with a different name to do what you want.

like image 53
MrFlick Avatar answered Mar 10 '26 12:03

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!