Skip to content

Count number of geometry primitives #202

@anthonynorth

Description

@anthonynorth

I'm trying to count the number of geometry primitives (point, linestring, polygon) per element. Is there a better / more direct approach than this?

wk_size <- function(handleable) {
  vector_meta <- wk::wk_vector_meta(handleable)
  feature_id <- seq_len(vector_meta$size)

  count <- wk:::wk_handle(
    handleable,
    wk::wk_flatten_filter(
      wk::wk_count_handler(),
      # ensure flat geoms
      max_depth = 1000L,
      add_details = TRUE
    )
  )

  count <- vctrs::new_data_frame(c(
    attr(count, "wk_details", exact = TRUE),
    count
  ))

  # get feature_ids and sizes
  feat_rle <- rle(count$feature_id)
  # or vctrs::vec_locate_sorted_groups(count$feature_id)

  # empty features may have been discarded from flatten. put those back
  idx <- match(feature_id, feat_rle$values)
  size <- replace(feat_rle$lengths[idx], is.na(idx), 0L)

  vctrs::new_data_frame(list(
    feature_id = feature_id,
    size = size
  ))
}

# example
wkt <- wk::wkt(c(
  "MULTIPOINT (1 1, 2 2)",
  "MULTIPOINT EMPTY",
  "POLYGON ((1 1))",
  "GEOMETRYCOLLECTION (POINT (1 1), MULTIPOLYGON (((2 2))))"
))

wk_size(wkt)
#>   feature_id size
#> 1          1    2
#> 2          2    0
#> 3          3    1
#> 4          4    2

Created on 2023-10-09 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions