@@ -452,6 +452,8 @@ module_xfaostat_L107_FoodBalanceSheet <- function(command, ...) {
452
452
453
453
# # b. For the sink items of the tier, separate balance into domestic and imported ----
454
454
# Note that the method here relies on Get_GROSS_EXTRACTION_RATE and Get_ARMINGTON_BALANCE
455
+ # Aggregate sink_items are aggregated into "sink_item"
456
+ # And production & processed are adjusted for primary aggregation
455
457
DF_CURR_NEST %> %
456
458
# adding bal_source including bal_import and bal_domestic
457
459
# map/allocate import to consumption
@@ -468,9 +470,9 @@ module_xfaostat_L107_FoodBalanceSheet <- function(command, ...) {
468
470
select(- extraction_rate ) - >
469
471
.df1
470
472
471
- # # c. Aggregate sink_items are aggregated into "sink_item" ----
472
- # And production & processed are adjusted for primary aggregation
473
- # Bind source items as well
473
+ # # c. Calculate source item shares ----
474
+ # in case that there are multiple source items, we need to do vertical aggregation carefully to avoid double accounting
475
+ # here we calculate the source shared by their processed uses
474
476
DF_ALL %> %
475
477
filter(nest_level < = curr_nest ) %> %
476
478
tidyr :: unnest(c(" data" )) %> %
@@ -576,8 +578,25 @@ module_xfaostat_L107_FoodBalanceSheet <- function(command, ...) {
576
578
ungroup() %> %
577
579
spread(element , value , fill = 0.0 ) %> %
578
580
# Do a final balance cleaning
581
+ # starting with stocks; the adj here is generaly very small
582
+ group_by(region_ID , APE_comm ) %> % dplyr :: arrange(- year ) %> %
583
+ mutate(`Stock Variation` = `Closing stocks` - `Opening stocks` ,
584
+ cum_StockVariation = cumsum(`Stock Variation` ) - first(`Stock Variation` ),
585
+ `Opening stocks1` = first(`Opening stocks` ) - cum_StockVariation ) %> %
586
+ select(- cum_StockVariation , - `Opening stocks` ) %> %
587
+ rename(`Opening stocks` = `Opening stocks1` ) %> %
588
+ mutate(`Closing stocks` = `Opening stocks` + `Stock Variation` ) %> %
589
+ mutate(Stockshifter = if_else(`Closing stocks` < 0 , abs(`Closing stocks` ), 0 )) %> %
590
+ mutate(Stockshifter = if_else(`Opening stocks` < 0 & `Opening stocks` < `Closing stocks` ,
591
+ abs(`Opening stocks` ), Stockshifter )) %> %
592
+ mutate(Stockshifter = max(Stockshifter ),
593
+ `Opening stocks` = `Opening stocks` + Stockshifter ,
594
+ `Closing stocks` = `Opening stocks` + `Stock Variation` ) %> %
595
+ select(- Stockshifter ) %> %
596
+ ungroup() %> %
597
+ # recalculate residuals
579
598
mutate(`Regional supply` = `Opening stocks` + Production + `Import` ,
580
- # ignore negative "processed" due to the above many-to-one processing above (should be small)
599
+ # ignore negative "processed" due to the above many-to-one processing above (mostly small)
581
600
Processed = if_else(Processed < 0 , 0 , Processed ),
582
601
Food = if_else(Food < 0 , 0 , Food ),
583
602
`Other uses` = if_else(`Other uses` < 0 , 0 , `Other uses` ),
0 commit comments