Custom function works only on some parent functions of another package

41 Views Asked by At

In my personal package I have a couple of functions that are used within the lidR package. I can't understand why the same function works if used with catalog_apply but gets an error if used with pixel_metrics. So, in the latter case, I have to load the single function in the Global environment to make it work.

Here an example code (ctg: catalog, shp: shapefile):

# code applied to the extracted field plots
> ads = clip_roi(ctg, shp, radius=shp$plot_rad) # extract plots
> opt_chunk_buffer(ads) <- 0
> opt_chunk_size(ads) <- 0
> opt_output_files(ads) <- ""

> metrics = catalog_apply(ads, cloud_metrics, func = .my_metrics)


# code applied to the whole area extent
> r = pixel_metrics(ctg, .my_metrics, res = gridRes)

error: cannot find function "my_metrics"

Taking inspiration from the author's work, my_metrics has been shortened to .my_metrics for a matter of ease, as follows:

#' @rdname my_metrics
#' @export
.my_metrics = ~my_metrics(X, Y, Z, ReturnNumber, Classification, ScanAngleRank, ht_slice=1, ht_max=NULL, min_pts=0, sar_thr=NULL)

Reading a bit around I thought that it could be probably related to this...but in my case the main packages used from the function (i.e. lidR, terra, sf) area already in the Depends section of the DESCRIPTION.

Might it be something related to how the lidR functions (i.e. cloud_metrics VS pixel_metrics) "interpret" mine?

1

There are 1 best solutions below

0
Mikko Marttila On

Looks like the pixel_metrics() call leads down a path where template_metrics() gets called and discards the environment associated with your .my_metrics formula. All that is left is the expression, so your my_metrics() function must be visible in the environment where that expression is eventually evaluated.

It's more difficult to work out why catalog_apply() does not behave like this. I'd recommend asking the package author for further clarification.