# \donttest{
library(sf)
library(dplyr)
library(ggplot2)
library(viridis)
# These are SYNTHETIC agricultural FSS data
data(ifs_dk) # Census data
ifs_weight = ifs_dk %>% dplyr::filter(Sample == 1) # Extract weighted subsample
# Create spatial data
ifg = fssgeo(ifs_dk, locAdj = "LL")
fsg = fssgeo(ifs_weight, locAdj = "LL")
# We use the numeric part of the farmtype to create a third variable. This
# is done for the an example, the value does not have any meaning when treated
# like this
ifg$ft = as.numeric(substr(ifg$FARMTYPE, 3, 4))^2
ress = c(1,5,10,20,40, 80, 160)*1000
# Create regular grid of the variables
ifl = gridData(ifg, vars = c("UAA", "UAAXK0000_ORG", "ft"), res = ress)
# Create the different multi-resolution grids
himg1 = multiResGrid(ifl, vars = "UAA", ifg = ifg, postProcess = FALSE)
himg2 = multiResGrid(ifl, vars = "UAAXK0000_ORG", ifg = ifg, postProcess = FALSE)
himg3 = multiResGrid(ifl, vars = "ft", ifg = ifg, postProcess = FALSE)
# The grids have different number of polygons
dim(himg1)
dim(himg2)
dim(himg3)
hh1 = MRGmerge(himg1, himg2, himg3 = himg3)
dim(hh1)
# Postprocessing can also be done on the merged object
hh11 = MRGmerge(himg1, himg2, himg3 = himg3, postProcess = TRUE, rounding = -1)
dim(hh11)
summary(hh1$UAA-hh11$UAA)
# Here the merging will instead redistribute average values to
# the higher resolution grid cells, and also seeing the effect
# of merging a third layer
hh2 = MRGmerge(himg1, himg2, aggr = "disaggr")
hh22 = MRGmerge(himg1, himg2, himg3 = himg3, aggr = "disaggr")
himg2$orgShare = himg2$UAAXK0000_ORG/himg2$res^2 * 10000
hh2$orgShare = hh2$UAAXK0000_ORG/hh2$res^2 * 10000
hh22$orgShare = hh22$UAAXK0000_ORG/hh22$res^2 * 10000
# Plot the organic share (organic area relative to grid cell area) for
# the original MRG grid for organic area, and after merging with the higher
# resolution maps.
p1 = ggplot(himg2) + geom_sf(aes(fill = orgShare)) + ggtitle("original") +
scale_fill_viridis()
p2 = ggplot(hh2) + geom_sf(aes(fill = orgShare)) + ggtitle("merged two")+
scale_fill_viridis()
p3 = ggplot(hh22) + geom_sf(aes(fill = orgShare)) + ggtitle("merged three")+
scale_fill_viridis()
if (require(patchwork)) p1 + p2 + p3 + plot_spacer() + plot_layout(guides = 'collect')
# If two data sets share the same variable, one of them has to be renamed.
# (A comparison of the two can act as a indication of possible errors
# introduced through the post-processing)
himg21 = multiResGrid(ifl, vars = c("UAA", "UAAXK0000_ORG"), ifg = ifg, postProcess = FALSE)
hh3 = try(MRGmerge(himg1, himg21, himg3 = himg3))
himg21 = himg21 %>% rename(UAA2 = UAA, weight_UAA2 = weight_UAA)
hh3 = MRGmerge(himg1, himg21, himg3 = himg3)
summary(hh3[, c("UAA", "UAA2")])
himg4 = multiResGrid(ifl, vars = c("UAA", "ft", "UAAXK0000_ORG"), ifg = ifg, postProcess = FALSE)
summary(hh1[, c("UAA", "UAAXK0000_ORG", "ft")])
summary(himg4[, c("UAA", "UAAXK0000_ORG", "ft")])
# }
Run the code above in your browser using DataLab