0

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?

Nico
  • 191
  • 1
  • 6
  • I can't tell from what you've written what functions are in your package and what are in a separate package. `catalog_apply` is in which package, yours or another? Same with `pixel_metrics`. It would help if you could more clearly delineate what is happening in your personal package and which specific pieces in your package are calling functions from another package. – joran May 30 '23 at 21:24
  • Please report a reproducible example on the github repo https://github.com/r-lidar/lidR – JRR Jun 06 '23 at 01:47

1 Answers1

2

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.

Mikko Marttila
  • 10,972
  • 18
  • 31