/
fs_functions.R
94 lines (76 loc) · 2.67 KB
/
fs_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
#' Built-in 'foot' functions
#' @description In addition to generic \code{R} functions (e.g. 'mean', 'max',
#' etc.), these functions are designed to provide simple access to common
#' calculations.
#' @param x numeric vector of values to summarize.
#' @return numeric value
#' @details These functions are designed to be used within
#' \code{\link[foot]{calculate_footstats}} which processes a \code{data.table}
#' by group ID. Therefore all functions take a vector of values and return a
#' single summary statistic. These functions are not likely to be used on
#' their own.
#' @name fs_functions
NULL
#> NULL
#' @rdname fs_functions
binary <- function(x){
return(ifelse(is.null(x), 0, 1))
}
#' @rdname fs_functions
count <- function(x){
return(length(x))
}
#' @rdname fs_functions
cv <- function(x){
res <- sd(x) / mean(x)
return(units::set_units(res, NULL))
}
#' @rdname fs_functions
entropy <- function(x){
bins <- cut(x, seq(5, 355, 10), labels=F) + 1
bins[is.na(bins)] <- 1
calc_ent <- -1 * sum(prop.table(table(bins)) * log(prop.table(table(bins))))
# normalizing step (see Boeing (2019))
hmax <- 3.584
hg <- 1.386
calc_ent <- 1 - ((calc_ent - hg) / (hmax - hg))^2
return(calc_ent)
}
#' @rdname fs_functions
majority <- function(x){
return(names(which.max(table(x))))
}
#' @rdname fs_functions
iqr <- function(x){
return(IQR(x, na.rm = TRUE))
}
# creating a function factory to use the pre-made function foot::fs_nnindex
#' Generate a nearest neighbour index function
#' @description Creates a new instance of the \code{fs_nnindex} function and
#' initialises it with zone and unit information.
#' @param zone A spatial polygon object of \code{sf} or \code{sp} type. If
#' omitted all observations in \code{X} are assumed to be within one zone and
#' the area of the minimum bounding circle is used for the nearest neighbour
#' index.
#' @param zoneField (Optional) Column name of unique identifiers in \code{zone}
#' to use. If omitted, the 'zoneID' will be numbered \code{1:nrow(zone)}.
#' @param unit character or \code{units} object to define distance. Default will
#' attempt to coerce units to meters.
#' @details This is a function factory. It creates a partial function in order
#' to allow \code{fs_nnindex} to be used by the internal loop of
#' \code{calculate_footstats}. This function will generally not be used on its
#' own.
#' @name gen_nnindex
gen_nnindex <- function(zone, zoneField=NULL, unit="m"){
force(zone)
force(zoneField)
force(unit)
function(x){
if(length(x) == 1){
return(0)
} else{
res <- fs_nnindex(sf::st_as_sf(x), zone, zoneField, unit)
return(res[["fs_nnindex"]])
}
}
}