-
Notifications
You must be signed in to change notification settings - Fork 0
/
combined_code.txt
5867 lines (5261 loc) · 198 KB
/
combined_code.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## File: app.R
# Source the UI and server components
source("ui.R")
source("server.R")
# Run the app
shinyApp(ui = ui, server = server)
## File: data.R
## data.R
#########################################
###
### Data manipulation within this section:
###
### >>> Census data
### > Further crops processing
### > Animal summary processing
### >>> Emissions data
### >>>
### >>> 2023 census module data
###
### --------------------------------
###
### How to update data:
###
### Individual instructions are available for each section.
###
### Inputted will need to be in the same format as previous iterations unless
### code is edited to adapt this.
###
### Current data within the section primarily comes from the publicly available publication tables.
###
### Download the most recent tables from the publication, add them to the project directory, and modify the file path.
###
### Data processing is designed to be robust, but small changes within publications will likely lead to bugs needing fixed
###
### Ensure when updating census information that the all subsections are updated below.
###
#########################################
# Libraries:
library(readxl)
library(openxlsx)
library(dplyr)
library(tidyr)
#########################################
###
###
### Census Data:
###
### Xlsx file originates from the published data tables in supporting documents
### 2023 version: https://www.gov.scot/publications/results-scottish-agricultural-census-june-2023/documents/
###
### To update, download the excel document and insert file into compendium working directory / file
### Insert file path in the file_path below.
### Check table_names for changes vs. the previous year's names and order
### If the order is incorrect, change the table number accordingly
###
### Try to avoid renaming tables below unless necessary as these are referenced throughout the app
### If changing any names, ensure all sourcing of the data matches changing (print_code.R can help to QA this)
###
### The data processing was designed for the 2023 census tables, and changes to tables may cause bugs
### Processing aims to standardise all tables to make them compatible with the different visualisation modules
### This includes removing the metadata above the tables, renaming headers, removing problematic trailing spaces, etc.
###
### Additional processing can be included if necessary (e.g. 2022 poultry removed to emphasise change in methodology)
### Some data processing could be moved from within the server pages in the app to speed up loading & improve efficiency
###
### To update, run the code below.
### QA results before saving as RData
### RData is then loaded within options.RData
###
### Ensure the rest of the census code is ran subsequently after updating the base tables.
###
#########################################
# Define file path
file_path <- "June+Agricultural+Census+2023+Tables.xlsx"
# Define the simplified table names and corresponding sheet names
table_names <- c(
"agricultural_area_hectares" = "Table_1",
"vegetables_bulbs_fruit_area" = "Table_2",
"number_of_cattle" = "Table_3 ", # this has a trailing space in the publication, if this gets fixed, change appropriately
"number_of_sheep" = "Table_4 ",
"number_of_pigs" = "Table_5",
"number_of_poultry" = "Table_6",
"number_of_other_livestock" = "Table_7",
"occupiers_employees" = "Table_8",
"occupiers_age_gender" = "Table_9",
"legal_responsibility" = "Table_10",
"owned_rented_land" = "Table_11",
"farm_type" = "Table_12",
"agricultural_area_lfa" = "Table_13",
"holdings_crops_grass_subregion" = "Table_14",
"crops_grass_area_subregion" = "Table_15",
"holdings_livestock_region_subregion" = "Table_16",
"livestock_subregion" = "Table_17",
"holdings_occupiers_employees_subregion" = "Table_18",
"occupiers_employees_subregion" = "Table_19",
"arable_rotation" = "Table_20",
"manure_fertiliser" = "Table_21"
)
# Function to remove rows until the first occurrence of "Source:" in the first column
remove_until_source <- function(data) {
# Remove the first row (which is now the original header row)
data <- data[-1, ]
# Now remove rows until the first occurrence of "Source:"
source_row <- which(str_detect(data[[1]], "^Source:"))
if (length(source_row) > 0) {
data <- data[(source_row + 1):nrow(data), ]
}
return(data)
}
# Function to remove columns and rows that are all NAs
clean_data <- function(data) {
data <- data[, colSums(is.na(data)) < nrow(data)] # Remove columns with all NAs
data <- data[rowSums(is.na(data)) < ncol(data), ] # Remove rows with all NAs
return(data)
}
# Function to clean header names by removing text within brackets, any '\r\n', extra spaces, and specific region names
clean_headers <- function(headers) {
headers <- str_replace_all(headers, "\\s*\\([^\\)]+\\)", "") # Remove text within brackets
headers <- str_replace_all(headers, "\r\n", " ") # Remove \r\n
headers <- str_replace_all(headers, "\\s+", " ") # Replace multiple spaces with a single space
headers <- str_replace_all(headers, "\\b(North West|North East|South East|South West)\\b", "") # Remove specific region names
headers <- str_trim(headers) # Trim again to remove any resulting leading or trailing spaces
# Make headers unique
headers <- make.unique(headers, sep = "_")
return(headers)
}
# Function to clean cell values by replacing multiple spaces with a single space
clean_cells <- function(data) {
data <- data %>% mutate(across(where(is.character), ~str_replace_all(.x, "\\s+", " ")))
return(data)
}
# Read each table, clean it, and assign to a variable
for (table in names(table_names)) {
sheet_name <- table_names[table]
data <- read_excel(file_path, sheet = sheet_name, col_names = FALSE) # Read data without headers
# Remove rows until the first occurrence of "Source:" in the first column
data <- remove_until_source(data)
# Clean headers manually since the first row was treated as data
headers <- as.character(data[1, ]) # Take the first row as headers
cleaned_headers <- clean_headers(headers)
# Remove the first row that is now the headers
data <- data[-1, ]
# Assign cleaned headers to the data
names(data) <- cleaned_headers
# Remove columns with '5 year' in the header (case insensitive)
columns_to_remove <- grep("5 year", cleaned_headers, ignore.case = TRUE)
if (length(columns_to_remove) > 0) {
data <- data[, -columns_to_remove]
cleaned_headers <- cleaned_headers[-columns_to_remove]
}
# Convert all columns except the first to numeric, setting non-numeric values to NA
data <- data %>% mutate(across(-1, ~ as.numeric(as.character(.))))
# Remove '\r\n' from all character columns and clean multiple spaces in the first column
data[[1]] <- str_replace_all(data[[1]], "\r\n", " ")
data <- clean_cells(data)
# Clean data
cleaned_data <- clean_data(data)
assign(table, cleaned_data)
}
# Set all values in the 2022 column to NA
number_of_poultry$`2022` <- NA
crops_grass_area_subregion <- crops_grass_area_subregion %>%
rename(`Na h-Eileanan Siar` = `Na h Eileanan Siar`)
# Save all tables to an RData file
save(list = names(table_names), file = "census_data.RData")
# load to test
#load("census_data.RData")
#################################
###
### Processing for Crops / Fruit / Veg
###
### Run the code below to update
###
### Run whenever census data is updated
###
#################################
# Print unique values
unique(agricultural_area_hectares$`Crop/Land use`)
unique(vegetables_bulbs_fruit_area$`Vegetables and fruits for human consumption`)
unique(crops_grass_area_subregion$`Land use by category`)
names(agricultural_area_hectares) <- names(agricultural_area_hectares) %>%
str_replace_all("Area", "") %>%
str_trim
names(vegetables_bulbs_fruit_area) <- names(vegetables_bulbs_fruit_area) %>%
str_replace_all("Area", "") %>%
str_trim
# Preprocess and round the summary crops data
crops_summary_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Total combine harvested crops", "Total crops for stockfeeding",
"Vegetables for human consumption", "Soft fruit")) %>%
pivot_longer(
cols = -`Crop/Land use`,
names_to = "Year",
values_to = "Value"
) %>%
mutate(
Year = as.numeric(Year), # Ensure Year is numeric
Value = if_else(
abs(as.numeric(Value)) >= 1000, # Round up for numbers with more than 3 significant figures
round(as.numeric(Value)),
round(as.numeric(Value), digits = 2)
)
)
land_use_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Total crops, fallow, and set-aside", "Total grass",
"Rough grazing", "Total sole right agricultural area", "Common grazings"))
land_use_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c("Total agricultural area", "Total grass and rough grazing",
"Sole right grazing", "Total crops and fallow", "Common grazing", "Woodland"))
# Subset for cereals data
cereals_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Wheat", "Triticale", "Winter barley", "Spring barley", "Barley Total",
"Winter oats", "Spring oats", "Oats Total", "Rye", "Mixed grain",
"Total cereals"))
# Subset for oilseeds data
oilseed_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Winter oilseed rape", "Spring oilseed rape", "Linseed", "Total oilseeds"))
# Subset for potatoes data
potatoes_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Seed potatoes", "Ware potatoes", "Total potatoes"))
# Subset for beans data
beans_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Protein peas", "Field beans"))
# Subset for animal feed data
stockfeeding_data <- agricultural_area_hectares %>%
filter(`Crop/Land use` %in% c("Turnips/swedes", "Kale/cabbage", "Maize", "Rape", "Fodder beet",
"Lupins", "Other crops for stockfeeding", "Total crops for stockfeeding"))
# Subset for human vegetables data
human_vegetables_data <- vegetables_bulbs_fruit_area %>%
filter(`Vegetables and fruits for human consumption` %in% c(
"Peas for canning, freezing or drying",
"Beans for canning, freezing or drying",
"Turnips/swedes",
"Calabrese",
"Cauliflower",
"Carrots",
"Other vegetables",
"Total vegetables"
))
# Subset for soft fruit data
fruit_data <- vegetables_bulbs_fruit_area %>%
filter(`Vegetables and fruits for human consumption` %in% c(
"Strawberries grown in the open",
"Raspberries grown in the open",
"Blueberries grown in the open",
"Blackcurrants and other fruit grown in the open",
"Total soft fruit grown in the open",
"Tomatoes grown under cover",
"Strawberries grown under cover",
"Raspberries grown under cover",
"Blueberries grown under cover",
"Other fruit grown under cover",
"Vegetables grown under cover",
"Strawberries grown in open/under cover",
"Raspberries grown in open/under cover",
"Blackcurrants grown in open/under cover",
"Blueberries grown in open/under cover",
"Tomatoes grown in open/under cover",
"Other fruit grown in open/under cover",
"Total soft fruit"
))
# Subset for cereals_subregion
cereals_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Wheat",
"Winter Barley",
"Spring Barley",
"Barley Total",
"Oats, triticale and mixed grain"
))
# Subset for oilseed_subregion
oilseed_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Rape for oilseed and linseed"
))
# Subset for potato_subregion
potatoes_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Potatoes"
))
# Subset for beans_subregion
beans_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Peas and beans for combining"
))
# Subset for stockfeeding_subregion
stockfeeding_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Stockfeeding crops"
))
# Subset for human_veg_subregion
human_vegetables_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Vegetables for human consumption"
))
# Subset for fruit_subregion
fruit_subregion <- crops_grass_area_subregion %>%
filter(`Land use by category` %in% c(
"Orchard and soft fruit"
))
# Saving all the subsets to an RData file
save(
crops_summary_data,
land_use_data,
land_use_subregion,
cereals_data,
oilseed_data,
potatoes_data,
beans_data,
stockfeeding_data,
human_vegetables_data,
fruit_data,
cereals_subregion,
oilseed_subregion,
potatoes_subregion,
beans_subregion,
stockfeeding_subregion,
human_vegetables_subregion,
fruit_subregion,
file = "crops_data.RData"
)
### Animals summary data - Requires census tables
load("census.RData")
# Convert the wide format data into long format using pivot_longer
number_of_pigs_long <- number_of_pigs %>%
pivot_longer(cols = -`Pigs by category`, names_to = "Year", values_to = "Total") %>%
filter(`Pigs by category` == "Total pigs") %>%
select(Year, `Total pigs` = Total)
number_of_poultry_long <- number_of_poultry %>%
pivot_longer(cols = -`Poultry by category`, names_to = "Year", values_to = "Total") %>%
filter(`Poultry by category` == "Total poultry") %>%
select(Year, `Total poultry` = Total)
number_of_sheep_long <- number_of_sheep %>%
pivot_longer(cols = -`Sheep by category`, names_to = "Year", values_to = "Total") %>%
filter(`Sheep by category` == "Total sheep") %>%
select(Year, `Total sheep` = Total)
number_of_cattle_long <- number_of_cattle %>%
pivot_longer(cols = -`Cattle by category`, names_to = "Year", values_to = "Total") %>%
filter(`Cattle by category` == "Total Cattle") %>%
select(Year, `Total cattle` = Total)
# Merge the dataframes on the 'Year' column
total_animals <- number_of_pigs_long %>%
inner_join(number_of_poultry_long, by = "Year") %>%
inner_join(number_of_sheep_long, by = "Year") %>%
inner_join(number_of_cattle_long, by = "Year")
# Convert Year column to numeric
total_animals$Year <- as.numeric(total_animals$Year)
# save total animals
save(total_animals, file = "total_animals.RData")
#########################################################################
###
###
### Emissions Data Processing
###
###
##########################################################################
#agri_gas = Gas Breakdown of Emissions from Scottish agriculture greenhouse gas emissions and nitrogen use
#subsector_total = Agricultural emissions broken down by subsector from Scottish agriculture greenhouse gas emissions and nitrogen use
#subsector_source = Breakdown of subsectors by source from Scottish agriculture greenhouse gas emissions and nitrogen use
#national_total = Yearly breakdown of Scottish Emissions from Scottish Greenhouse Gas Emissions publication
# As of 2022-23 emissions publication, these were made available in excel sheet before being inputted into R
# This could be repeated, or data could be read in from the difference sources, and manipulated into the same format
# To update data, replace file path and run the below script.
# Load data from the Excel file
file_path <- "ghg_data.xlsx"
agri_gas <- read_excel(file_path, sheet = "agri_gas")
national_total <- read_excel(file_path, sheet = "national_total")
subsector_total <- read_excel(file_path, sheet = "subsector_total")
subsector_source <- read_excel(file_path, sheet = "subsector_source")
agri_gas <- agri_gas %>%
rename(Gas = ...1)
# Reshape the data to long format
agri_gas <- agri_gas %>% pivot_longer(cols = -Gas, names_to = "Year", values_to = "Value")
national_total <- national_total %>% pivot_longer(cols = -Industry, names_to = "Year", values_to = "Value")
subsector_total <- subsector_total %>% pivot_longer(cols = -Subsector, names_to = "Year", values_to = "Value")
# Convert Year to numeric
agri_gas$Year <- as.numeric(agri_gas$Year)
national_total$Year <- as.numeric(national_total$Year)
subsector_total$Year <- as.numeric(subsector_total$Year)
# Merge the specified sources into 'Other emission source'
subsector_source <- subsector_source %>%
mutate(
Source = ifelse(Source %in% c("Urea application", "Non-energy products from fuels and solvent use", "Other emission source"),
"Other emission source",
Source)
) %>%
group_by(Source) %>%
summarise(across(everything(), sum)) %>%
ungroup()
save(subsector_total, agri_gas, national_total, subsector_source, file = "ghg_data.RData")
# load data to test
#load("ghg_data.RData")
################################################################################
###############################
####
#### Module 2023 data
####
#### This data comes from the 2023 Agricultural Census Module Results
####
#### https://www.gov.scot/publications/results-from-the-scottish-agricultural-census-module-june-2023/
####
#### The script extracts tables looking at soil management, fertiliser usage, manure, nitrogen
#### and formats the data into formatting to be used in the modules.
#### This minimises the amount of data processing done within the R Shiny app, improving running efficiency.
####
#### This script should not need re-run as the module data will not be updated, though can be used
#### as a baseline to include future year's module data.
####
#################################
# Load necessary libraries
library(readxl)
library(stringr)
library(dplyr)
# Define the file path
file_path <- "June+Agricultural+Census+2023+-+Module+Report+-+Production+methods+and+nutrient+application+-+Tables.xlsx"
# Define the sheet names to read
sheets_to_read <- c("Table_4", "Table_5", "Table_7", "Table_8", "Table_9", "Table_12")
# Define shortened names for the dataframes
short_names <- c("soil_nutrient_mgmt", "grass_crop_nutrient_mgmt", "nitrogen_250",
"nitrogen_400", "manure_qty", "fertiliser_use")
# Function to clean header names by removing text within brackets, any '\r\n', extra spaces, and specific region names
clean_headers <- function(headers) {
headers <- str_replace_all(headers, "\\s*\\([^\\)]+\\)", "") # Remove text within brackets
headers <- str_replace_all(headers, "\r\n", " ") # Remove \r\n
headers <- str_replace_all(headers, "\\s+", " ") # Replace multiple spaces with a single space
headers <- str_replace_all(headers, "\\b(North West|North East|South East|South West)\\b", "") # Remove specific region names
headers <- str_trim(headers) # Trim again to remove any resulting leading or trailing spaces
return(headers)
}
# Function to read and process each sheet
read_and_process_sheet <- function(sheet) {
df <- read_excel(file_path, sheet = sheet, skip = 5) # Skip the first 5 rows
colnames(df) <- clean_headers(colnames(df)) # Clean the headers
return(df)
}
# Function to round all numeric columns to 2 decimal places
round_df <- function(df) {
df[] <- lapply(df, function(x) if(is.numeric(x)) round(x, 2) else x)
return(df)
}
# Read and process the specified sheets into a list of dataframes
data_frames <- lapply(sheets_to_read, read_and_process_sheet)
# Name the list elements with shortened names
names(data_frames) <- short_names
# Remove the 'Area' column from 'grass_crop_nutrient_mgmt' if it exists
if("Area" %in% colnames(data_frames$grass_crop_nutrient_mgmt)) {
data_frames$grass_crop_nutrient_mgmt <- select(data_frames$grass_crop_nutrient_mgmt, -Area)
}
# Ensure 'Percentage of holdings' and 'Average holding area' are numeric in both dataframes
data_frames$soil_nutrient_mgmt$`Percentage of holdings` <- as.numeric(as.character(data_frames$soil_nutrient_mgmt$`Percentage of holdings`))
data_frames$grass_crop_nutrient_mgmt$`Percentage of holdings` <- as.numeric(as.character(data_frames$grass_crop_nutrient_mgmt$`Percentage of holdings`))
data_frames$soil_nutrient_mgmt$`Average holding area` <- as.numeric(as.character(data_frames$soil_nutrient_mgmt$`Average holding area`))
data_frames$grass_crop_nutrient_mgmt$`Average holding area` <- as.numeric(as.character(data_frames$grass_crop_nutrient_mgmt$`Average holding area`))
# Round all numeric columns to 2 decimal places in each dataframe
data_frames <- lapply(data_frames, round_df)
# Join 'soil_nutrient_mgmt' and 'grass_crop_nutrient_mgmt' data frames
combined_nutrient_mgmt <- bind_rows(data_frames$soil_nutrient_mgmt, data_frames$grass_crop_nutrient_mgmt)
# Remove specified rows from the 'Soil nutrient management' column in the combined data frame
remove_entries <- c("Holdings with grassland", "Cropland holdings", "Holdings with grass or crops",
"Soil testing resulted in change of crop nutrient application (those that performed soil testing)",
"Uses protected urea")
combined_nutrient_mgmt <- combined_nutrient_mgmt %>%
filter(!`Soil nutrient management` %in% remove_entries)
# Assign the combined data frame back to the list
data_frames$combined_nutrient_mgmt <- combined_nutrient_mgmt
# Remove the original separate data frames
data_frames$soil_nutrient_mgmt <- NULL
data_frames$grass_crop_nutrient_mgmt <- NULL
# Save the data frames as a .RData file
save(list = names(data_frames), file = "module_2023.RData", envir = list2env(data_frames))
################################
## File: hc_theme.R
# hc_theme.R
library(highcharter)
# Define the Highcharts theme
thm <- hc_theme(
chart = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
title = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
subtitle = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
xAxis = list(
labels = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
title = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
)
),
yAxis = list(
labels = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
title = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
)
),
tooltip = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
),
headerFormat = "<b>{point.key}</b><br/>"
),
legend = list(
itemStyle = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
)
),
plotOptions = list(
series = list(
stickyTracking = FALSE,
itemStyle = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px",
color = "black"
),
dataLabels = list(
style = list(
fontFamily = "Arial, sans-serif",
fontSize = "16px", # Increase the font size for data labels
color = "black"
)
),
marker = list(
enabled = TRUE,
states = list(
hover = list(
enabled = TRUE
)
)
)
)
),
colors = c("#002d54", "#2b9c93", "#6a2063", "#e5682a", "#0b4c0b", "#5d9f3c", "#592c20", "#ca72a2")
)
# Apply the Highcharts theme globally
options(highcharter.theme = thm)
## File: home.R
## File: module_animals_summary.R
# module_summary_animals.R
# Reactive data setup for Animals
full_data_animals <- reactive({
total_animals %>%
pivot_longer(
cols = starts_with("Total"),
names_to = "Animal_Type",
values_to = "Value"
) %>%
mutate(Value = as.numeric(Value)) # Ensure the 'Value' column is numeric
})
animalsSummaryUI <- function(id) {
ns <- NS(id)
tagList(
sidebarLayout(
sidebarPanel(
width = 3,
div("Adjust the sliders to compare data from different years.",
style = "font-size: 14px; font-weight: bold; margin-bottom: 10px;"),
sliderInput(ns("summary_current_year_animals"), "Year of interest", min = 2012, max = census_year, value = census_year, step = 1, sep = ""),
sliderInput(ns("summary_comparison_year_animals"), "Comparison year", min = 2012, max = census_year, value = census_year - 1, step = 1, sep = "")
),
mainPanel(
id = ns("mainpanel"),
width = 9,
tabsetPanel(
id = ns("tabs"),
tabPanel("Summary Page",
value = "Summary_Page",
fluidRow(
column(width = 6, valueBoxUI(ns("totalCattle")), style = "padding-right: 0; padding-left: 0; padding-bottom: 10px;"),
column(width = 6, valueBoxUI(ns("totalSheep")), style = "padding-right: 0; padding-left: 0; padding-bottom: 10px;")
),
fluidRow(
column(width = 6, valueBoxUI(ns("totalPigs")), style = "padding-right: 0; padding-left: 0;"),
column(width = 6, valueBoxUI(ns("totalPoultry")), style = "padding-right: 0; padding-left: 0;")
),
# Add the footer text
div(
style = "margin-top: 20px; padding: 10px; border-top: 1px solid #ddd;",
HTML("<strong>Note:</strong> Poultry estimates for 2023 are not comparable to previous years due to methodological improvements.")
)
),
tabPanel("Data Table",
fluidRow(
column(12,
DTOutput(ns("data_table")),
tags$div(
style = "margin-top: 20px;",
downloadButton(ns("download_data"), "Download Data")
)
)
)
),
footer = generateCensusTableFooter()
)
)
)
)
}
animalsSummaryServer <- function(id) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
current_year <- reactive({ input$summary_current_year_animals })
comparison_year <- reactive({ input$summary_comparison_year_animals })
valueBoxServer("totalCattle", full_data_animals, "Animal_Type", reactive("Total cattle"), current_year, comparison_year, "cattle")
valueBoxServer("totalSheep", full_data_animals, "Animal_Type", reactive("Total sheep"), current_year, comparison_year, "sheep")
valueBoxServer("totalPigs", full_data_animals, "Animal_Type", reactive("Total pigs"), current_year, comparison_year, "pigs")
valueBoxServer("totalPoultry", full_data_animals, "Animal_Type", reactive("Total poultry"), current_year, comparison_year, "poultry")
# Pivot the data wider
pivoted_data <- reactive({
full_data_animals() %>%
pivot_wider(names_from = Animal_Type, values_from = Value) %>%
mutate(across(where(is.numeric) & !contains("Year"), comma))
})
# Render the pivoted data table
output$data_table <- renderDT({
datatable(pivoted_data(), options = list(
scrollX = TRUE, # Enable horizontal scrolling
pageLength = 20 # Show 20 entries by default
))
})
# Download handler for the pivoted data
output$download_data <- downloadHandler(
filename = function() {
paste("Animal_Summary_Data_", Sys.Date(), ".csv", sep = "")
},
content = function(file) {
write.csv(pivoted_data(), file, row.names = FALSE)
}
)
})
}
# Testing module
content_demo <- function() {
ui <- fluidPage(animalsSummaryUI("summary_animals_test"))
server <- function(input, output, session) {
animalsSummaryServer("summary_animals_test")
}
shinyApp(ui, server)
}
content_demo()
## File: module_area_chart.R
## File: module_bar_chart.R
## File: module_beans.R
# File: module_beans.R
beansUI <- function(id) {
ns <- NS(id)
sidebarLayout(
sidebarPanel(
width = 3,
conditionalPanel(
condition = "input.tabsetPanel === 'Map'",
ns = ns,
radioButtons(
ns("variable"),
"Select Variable",
choices = unique(beans_subregion$`Land use by category`)
)
),
conditionalPanel(
condition = "input.tabsetPanel === 'Time Series' || input.tabsetPanel === 'Area Chart'",
ns = ns,
checkboxGroupInput(
ns("timeseries_variables"),
"Select Time Series Variables",
choices = unique(beans_data$`Crop/Land use`),
selected = c(
"Protein peas",
"Field beans"
)
)
),
conditionalPanel(
condition = "input.tabsetPanel === 'Data Table'",
ns = ns,
radioButtons(
ns("table_data"),
"Select Data to Display",
choices = c("Map Data" = "map", "Time Series Data" = "timeseries"),
selected = "map"
)
)
),
mainPanel(
width = 9,
tabsetPanel(
id = ns("tabsetPanel"),
tabPanel("Map", mapUI(ns("map"))),
tabPanel("Time Series", lineChartUI(ns("line"))),
tabPanel("Area Chart", areaChartUI(ns("area"))),
tabPanel("Data Table",
DTOutput(ns("table")),
downloadButton(ns("download_data"), "Download Data"),
generateCensusTableFooter()
)
)
)
)
}
beansServer <- function(id) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
beans_map <- beans_subregion %>%
select(-Scotland) %>%
mutate(across(everything(), as.character)) %>%
pivot_longer(cols = -`Land use by category`, names_to = "sub_region", values_to = "value") %>%
mutate(value = safe_as_numeric(value))
mapServer(
id = "map",
data = reactive({
req(input$variable)
beans_map %>% filter(`Land use by category` == input$variable)
}),
unit = "hectares",
footer = census_footer,
variable = reactive(input$variable),
title = paste("Beans distribution by region in Scotland in", census_year),
legend_title = "Area (hectares)"
)
chart_data <- reactive({
req(input$timeseries_variables)
filtered_data <- beans_data %>%
filter(`Crop/Land use` %in% input$timeseries_variables) %>%
pivot_longer(cols = -`Crop/Land use`, names_to = "year", values_to = "value") %>%
mutate(year = as.numeric(year)) # Ensure year is numeric
filtered_data
})
areaChartServer(
id = "area",
chart_data = chart_data,
title = paste("Area used to grow peas and/or beans
over time"),
yAxisTitle = "Area of peas/beans (1,000 hectares)",
xAxisTitle = "Year",
unit = "hectares",
footer = census_footer,
x_col = "year",
y_col = "value"
)
lineChartServer(
id = "line",
chart_data = chart_data,
title = paste("Area used to grow peas and/or beans
over time"),
yAxisTitle = "Area of peas/beans (1,000 hectares)",
xAxisTitle = "Year",
unit = "hectares",
footer = census_footer,
x_col = "year",
y_col = "value"
)
output$table <- renderDT({
req(input$tabsetPanel == "Data Table")
if (input$table_data == "map") {
req(input$variable)
datatable(
beans_map %>%
filter(`Land use by category` == input$variable) %>%
pivot_wider(names_from = sub_region, values_from = value) %>%
mutate(across(where(is.numeric), comma)), # Apply comma formatting to numeric columns
options = list(scrollX = TRUE) # Enable horizontal scrolling
)
} else {
datatable(
beans_data %>%
pivot_wider(names_from = year, values_from = value) %>%
mutate(across(where(is.numeric) & !contains("Year"), comma)), # Apply comma formatting to numeric columns except 'Year'
options = list(scrollX = TRUE) # Enable horizontal scrolling
)
}
})
output$download_data <- downloadHandler(
filename = function() {
if (input$table_data == "map") {
paste("Beans_Subregion_Data_", Sys.Date(), ".csv", sep = "")
} else {
paste("Beans_Timeseries_Data_", Sys.Date(), ".csv", sep = "")
}
},
content = function(file) {
data <- if (input$table_data == "map") {
beans_map %>%
filter(`Land use by category` == input$variable) %>%
pivot_wider(names_from = sub_region, values_from = value)
} else {
beans_data %>%
pivot_longer(cols = -`Crop/Land use`, names_to = "year", values_to = "value") %>%
pivot_wider(names_from = year, values_from = value)
}
write.csv(data, file, row.names = FALSE)
}
)
})
}
beans_demo <- function() {
ui <- fluidPage(beansUI("beans_test"))
server <- function(input, output, session) {
beansServer("beans_test")
}
shinyApp(ui, server)
}
beans_demo()
## File: module_breakdown_chart.R
## File: module_cattle.R
# File: module_cattle.R
cattleUI <- function(id) {
ns <- NS(id)
sidebarLayout(
sidebarPanel(
width = 3,
conditionalPanel(
condition = "input.tabsetPanel === 'Map'",
ns = ns,
radioButtons(