-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuns.R
More file actions
35 lines (29 loc) · 1.14 KB
/
funs.R
File metadata and controls
35 lines (29 loc) · 1.14 KB
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
# From https://alistaire.rbind.io/blog/coalescing-joins/
coalesce_join <- function(x, y,
by = NULL, suffix = c(".x", ".y"),
join = dplyr::full_join, ...) {
joined <- join(x, y, by = by, suffix = suffix, ...)
# names of desired output
cols <- union(names(x), names(y))
to_coalesce <- names(joined)[!names(joined) %in% cols]
suffix_used <- suffix[ifelse(endsWith(to_coalesce, suffix[1]), 1, 2)]
# remove suffixes and deduplicate
to_coalesce <- unique(substr(
to_coalesce,
1,
nchar(to_coalesce) - nchar(suffix_used)
))
coalesced <- purrr::map_dfc(to_coalesce, ~dplyr::coalesce(
joined[[paste0(.x, suffix[1])]],
joined[[paste0(.x, suffix[2])]]
))
names(coalesced) <- to_coalesce
dplyr::bind_cols(joined, coalesced)[cols]
}
# Convenience functions for counting the number of points in a tract + mutating, and calculating distance to closest point
tractcount <- function(j,k) {
sapply(st_geometry(j), function(x) suppressMessages(st_within(k,x,sparse = FALSE)) %>% sum)
}
tractdist <- function(j,k) {
st_distance(st_geometry(j),k) %>% apply(.,1,min)
}