diff --git a/ext/RbaseTerraExt/RbaseTerraExt.jl b/ext/RbaseTerraExt/RbaseTerraExt.jl index 8f50b0b..9a4cf61 100644 --- a/ext/RbaseTerraExt/RbaseTerraExt.jl +++ b/ext/RbaseTerraExt/RbaseTerraExt.jl @@ -6,8 +6,12 @@ using RCall, NetCDFTools function init_pkgs() R""" - library(terra) - library(exactextractr) + suppressMessages({ + library(Ipaper) + library(terra) + library(exactextractr) + library(data.table) + }) aperm_array <- function(x) { dims = dim(x) @@ -89,4 +93,29 @@ function NetCDFTools.exact_extract(data, lon, lat, shp, date=nothing; plot=false """ |> rcopy end + +function NetCDFTools.coverage_fraction(f, shp) + init_pkgs() + + R""" + ra = rast($f, lyrs=1) + + shp = sf::read_sf($shp) + fraction = exactextractr::coverage_fraction(ra, shp)[[1]] + area = cellSize(ra, unit = "km") + + r = c(area, fraction = fraction) + rast_df(r) %>% + mutate(area2 = area * fraction) %>% + .[fraction > 0] %>% + .[, .(I = cell, cell, lon, lat, fraction, area, area2)] + # print(info) + # info + """ |> rcopy +end + +# TODO: Test convert julia `Raster` to R `terra::rast` + + + end diff --git a/src/tools_rbase.jl b/src/tools_rbase.jl index 65e8782..cf3cd7a 100644 --- a/src/tools_rbase.jl +++ b/src/tools_rbase.jl @@ -1,3 +1,5 @@ function exact_extract end -export exact_extract +function coverage_fraction end + +export exact_extract, coverage_fraction