-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.R
92 lines (75 loc) · 2.52 KB
/
functions.R
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
####################################################################################
# Functions for load.R
####################################################################################
# Clean dollar amounts function
clean_dollar <- function(str) {
return(
str %>%
str_trim() %>%
str_remove("[$]") %>%
str_remove(",") %>%
as.numeric()
)
}
# Clean organisation name function
clean_name <- function(str) {
return(
str %>%
str_trim() %>%
str_remove("\r\n ")
)
}
# Function to allocate grants to electorates
allocate_electorate <- function(points_ls, electorates_sf) {
# Dataframe with SA1 names and placeholder electorate
assign_df <- points_ls$dataframe %>%
mutate(electorate = 0)
# Loop through point-in-polygon checking
for (i in 1:length(points_ls$coords)) {
# Print for progress tracking
if (i %% 100 == 0) {print(i)}
# Extract coord
coord <- points_ls$coords[i]
coord_state <- points_ls$dataframe$State[i]
# Loop through electorates (in state if possible - for efficiency)
# if (coord_state %in% unique(electorates_sf$state)) {
#
# # Get polygons in state only
# state_electorates_sf <- subset(electorates_sf, state == coord_state)
#
# # Loop through electorates to assign
# for (j in 1:length(state_electorates_sf@polygons)) {
#
# # Electorate name and polygon
# electorate_name <- state_electorates_sf$elect_div[j]
# electorate_poly <- subset(state_electorates_sf, elect_div == electorate_name)
#
# # Does it contain coord
# electorate_contains = gContains(electorate_poly, coord)
#
# if (electorate_contains == TRUE) {
# assign_df$electorate[i] = electorate_name
# break
# }
#
# }
#
# } else { # Not assigned to state, must check all electorates
# Loop through electorates to assign
for (j in 1:length(electorates_sf@polygons)) {
# Electorate name and polygon
electorate_name <- electorates_sf$elect_div[j]
electorate_poly <- subset(electorates_sf, elect_div == electorate_name)
# Does it contain coord
electorate_contains = gContains(electorate_poly, coord)
if (electorate_contains == TRUE) {
assign_df$electorate[i] = electorate_name
break
}
}
# }
}
# assign_df <- assign_df %>%
# filter(electorate != 0)
return(assign_df)
}