David LeBauer
David LeBauer

Reputation: 31751

How to find out which (version of a) function is being used?

Question:

How can I find out which version of a function is being called? For example, if I use unique on a data.frame, I presume that I am using unique.data.frame. However, there is no unique.raster function, although there is a raster::unique. But if I use, e.g., trace(unique), I only get information that the unique function is being used.

I'd like to confirm, for example, that when I call unique(data.frame(1)), unique.data.frame is being called.

Example:

I am having trouble figuring out why unique(raster_object) works at the command line but not inside a function. Apparently, unique.default is being called inside the function, so I would like to explicitly state which `unique.&

For example this works:

library(raster)
a <- rasterFromXYZ(data.frame(a=1:2,b=2:3,c=3:4))
unique(a)

But when I put this in a function:

myfun <- function(){
  a <- rasterFromXYZ(data.frame(a=1:2,b=2:3,c=3:4))
  b <- crop(a, extent(c(1,2,3,4)))
  unique(a)
}

even if the package uses raster as a dependency, after I build the package and load it in a new R session, I get the error:

> myfun()
Error in unique.default(a) : unique() applies only to vectors

Even though sessionInfo() shows that the raster package is loaded.

and if I use debug(unique), it doesn't seem to be telling me which function is being called:

Browse[6]> unique(a)
Error in unique.default(a) : unique() applies only to vectors
Browse[6]> raster::unique(a)
debugging in: raster::unique(a)
debug: standardGeneric("unique")

Upvotes: 3

Views: 1273

Answers (1)

IRTFM
IRTFM

Reputation: 263391

 myfun <- function(){
   a <- rasterFromXYZ(data.frame(a=1:2,b=2:3,c=3:4))
   b <- crop(a, extent(c(1,2,3,4)))
   raster::unique(a)
 }
 myfun()
#[1] 3 4

If there were a unique.raster dispatched in the S3 system, you could have used trace(unique), but since the unique method for class "rasterLayer" is an S4 function, that won't work:

> showMethods("unique")
Function: unique (package base)
x="ANY", incomparables="ANY"
x="character", incomparables="missing"
    (inherited from: x="ANY", incomparables="ANY")
x="numeric", incomparables="missing"
    (inherited from: x="ANY", incomparables="ANY")
x="RasterLayer", incomparables="missing"
x="RasterStackBrick", incomparables="missing"

Use it's package location:

> trace("unique", browser, where=raster)
Tracing function "unique" as seen from package "raster"
[1] "unique"
> myfun()
Tracing unique(xyz[, 1]) on entry 
Called from: eval(expr, envir, enclos)
Browse[1]> 
Browse[1]> c
[1] 3 4
> untrace()
Error in methods::.TraceWithMethods(where = <environment>, untrace = TRUE) : 
  argument "what" is missing, with no default
> untrace("unique",  where=raster)
Untracing function "unique" as seen from package "raster"

Upvotes: 2

Related Questions