Skip to content

Commit

Permalink
match gdptools weight method
Browse files Browse the repository at this point in the history
  • Loading branch information
dblodgett-usgs committed Nov 19, 2024
1 parent 8fce8f5 commit f9e91b8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
8 changes: 4 additions & 4 deletions R/calculate_area_intersection_weights.R
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ calculate_area_intersection_weights <- function(x, y, normalize, allow_lonlat =
areaWeight = "areaWeight_x_y")

} else {
# for normalized, we sum the intersection area by the total target intersection area
int <- ungroup(mutate(group_by(int, vary),
totalArea_y = sum(.data$area_intersection)))

# for normalized, we sum the intersection area by the total target area
int <- left_join(int, data.frame(vary = y$vary,
totalArea_y = as.numeric(sf::st_area(y))), by = "vary")

int <- areal::aw_weight(int,
areaVar = "area_intersection",
Expand Down
5 changes: 3 additions & 2 deletions tests/testthat/test_area_weighted.R
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@ test_that("extended_example", {

(y_x_norm <- calculate_area_intersection_weights(y, x, normalize = TRUE))

expect_true(all(dplyr::summarize(dplyr::group_by(y_x_norm, idx), w = sum(w))$w == 1))
expect_equal(dplyr::summarize(dplyr::group_by(y_x_norm, idx), w = sum(w))$w,
c(1, .25, .5, .5))

# and to use these in an area weighted sum we need the area of each polygon in
# the source data (x)
Expand All @@ -190,7 +191,7 @@ test_that("extended_example", {
dplyr::mutate(val = ifelse(is.na(w), NA, val)) |>
dplyr::group_by(idx) |> # group so we get one row per `x`
# now we weight by the percent of the area from each polygon in `x` per polygon in `y`
dplyr::mutate(new_val = sum( (val * w), na.rm = TRUE )))
dplyr::mutate(new_val = sum( (val * w), na.rm = TRUE ) / sum(w, na.rm = TRUE)))

# summarize to show the result
(z_y_x_norm <- dplyr::summarise(z_y_x_norm, new_val = unique(new_val)))
Expand Down

0 comments on commit f9e91b8

Please sign in to comment.