6

I want to calculate grid_metrics() for several fields of my point cloud, using several functions. I want to perform this in loops to make my code look cleaner.

Basically I want this:

# loop through fields
 for (name in c("field1", "field2", "field3")) {
    # loop through statistics
    for (type in list(c("mean", mean), c("sd", sd))) {
      # calculate gris metrics
      raster <- grid_metrics(point_cloud, ~type[[2]](name), res = 1)

However, this does not work. Using the statistic I specified works. However, whatever I tried, I did not manage to replace the field name with a variable containing the name. I always get the warning In mean.default(name) : argument is not numeric or logical: returning NA.

I found a workaround using rasterize(), but then these rasters have an offset to my other rasters created with grid_metrics() and I think it would be better to create all rasters consistently in the same way.

(Here the workaround:)

raster <- rasterize(data.frame(X=point_cloud@data$X, Y=point_cloud@data$Y),
                    raster_object, field=get(name, point_cloud@data), fun = type[[2]])

Can someone help me to replace the column name with a variable? Putting an eval() around the variable does not help either.

1 Answer 1

6

That sounds overly complex and computationally inefficient. Why don't you compute all your metrics at once?

mymetrics = function(f1,f2,f3) {
  list(
   avgf1 = mean(f1),
   sdf2 = sd(f1),
   avgf2 = mean(f2),
   sdf2 = sd(f2),
   avgf3 = mean(f3),
   sdf3 = sd(f3))
}


grid_metrics(point_cloud, ~mymetrics(field1, field2, field3), res = 1)

Anyway if you really prefer to build custom calls in a loop I would go for building an expression from a concatenated string.

name = "Intensity"
type = "mean"
expr = paste0("~", type, "(", name, ")")
expr = eval(parse(text = expr))
raster <- grid_metrics(point_cloud, expr, res = 20)
2
  • Thanks! I thought calculating the bands separately maybe takes longer, but spares my RAM more, since I only have 16GB. I guess I have to decide what's more important.
    – Zoe
    Commented May 9, 2021 at 12:27
  • 2
    Computation of raster does not take a lot of ram actually. If you are concerned by memory you can always process by chunk with a LAScatalog
    – JRR
    Commented May 9, 2021 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.