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
|
#' Distance between two locations
#'
#' `step_geodist` creates a *specification* of a
#' recipe step that will calculate the distance between
#' points on a map to a reference location.
#'
#' @inheritParams step_pca
#' @inheritParams step_center
#' @param lon,lat Selector functions to choose which variables are
#' used by the step. See [selections()] for more details.
#' @param ref_lon,ref_lat Single numeric values for the location
#' of the reference point.
#' @param is_lat_lon A logical: Are coordinates in latitude and longitude? If
#' `TRUE` the Haversine formula is used and the returned result is meters. If
#' `FALSE` the Pythagorean formula is used. Default is `TRUE` and for recipes
#' created from previous versions of recipes, a value of `FALSE` is used.
#' @param log A logical: should the distance be transformed by
#' the natural log function?
#' @param columns A character string of variable names that will
#' be populated (eventually) by the `terms` argument.
#' @param name A single character value to use for the new
#' predictor column. If a column exists with this name, an error is
#' issued.
#' @template step-return
#' @family multivariate transformation steps
#' @references https://en.wikipedia.org/wiki/Haversine_formula
#' @export
#' @details `step_geodist` uses the Pythagorean theorem to calculate Euclidean
#' distances if `is_lat_lon` is FALSE. If `is_lat_lon` is TRUE, the Haversine
#' formula is used to calculate the great-circle distance in meters.
#'
#' # Tidying
#'
#' When you [`tidy()`][tidy.recipe()] this step, a tibble with columns
#' echoing the values of `lat`, `lon`, `ref_lat`, `ref_lon`,
#' `is_lat_lon`, `name`, and `id` is returned.
#'
#' @template case-weights-not-supported
#'
#' @examplesIf rlang::is_installed("modeldata")
#' data(Smithsonian, package = "modeldata")
#'
#' # How close are the museums to Union Station?
#' near_station <- recipe(~., data = Smithsonian) %>%
#' update_role(name, new_role = "location") %>%
#' step_geodist(
#' lat = latitude, lon = longitude, log = FALSE,
#' ref_lat = 38.8986312, ref_lon = -77.0062457,
#' is_lat_lon = TRUE
#' ) %>%
#' prep(training = Smithsonian)
#'
#' bake(near_station, new_data = NULL) %>%
#' arrange(geo_dist)
#'
#' tidy(near_station, number = 1)
step_geodist <- function(recipe,
lat = NULL,
lon = NULL,
role = "predictor",
trained = FALSE,
ref_lat = NULL,
ref_lon = NULL,
is_lat_lon = TRUE,
log = FALSE,
name = "geo_dist",
columns = NULL,
skip = FALSE,
id = rand_id("geodist")) {
if (length(ref_lon) != 1 || !is.numeric(ref_lon)) {
rlang::abort("`ref_lon` should be a single numeric value.")
}
if (length(ref_lat) != 1 || !is.numeric(ref_lat)) {
rlang::abort("`ref_lat` should be a single numeric value.")
}
if (length(is_lat_lon) != 1 || !is.logical(is_lat_lon)) {
rlang::abort("`is_lat_lon` should be a single logical value.")
}
if (length(log) != 1 || !is.logical(log)) {
rlang::abort("`log` should be a single logical value.")
}
if (length(name) != 1 || !is.character(name)) {
rlang::abort("`name` should be a single character value.")
}
if (is_lat_lon && abs(ref_lat) > 90.0) {
rlang::abort("`ref_lat` should be between -90 and 90")
}
if (is_lat_lon && abs(ref_lon) > 180.0) {
rlang::abort("`ref_lon` should be between -180 and 180")
}
add_step(
recipe,
step_geodist_new(
lon = enquos(lon),
lat = enquos(lat),
role = role,
trained = trained,
ref_lon = ref_lon,
ref_lat = ref_lat,
is_lat_lon = is_lat_lon,
log = log,
name = name,
columns = columns,
skip = skip,
id = id
)
)
}
step_geodist_new <-
function(lon, lat, role, trained, ref_lon, ref_lat, is_lat_lon,
log, name, columns, skip, id) {
step(
subclass = "geodist",
lon = lon,
lat = lat,
role = role,
trained = trained,
ref_lon = ref_lon,
ref_lat = ref_lat,
is_lat_lon = is_lat_lon,
log = log,
name = name,
columns = columns,
skip = skip,
id = id
)
}
# for backward compatibility
check_is_lat_lon <- function(x) {
if (!"is_lat_lon" %in% names(x)) {
x$is_lat_lon <- FALSE
}
x
}
#' @export
prep.step_geodist <- function(x, training, info = NULL, ...) {
lon_name <- recipes_eval_select(x$lon, training, info)
lat_name <- recipes_eval_select(x$lat, training, info)
check_type(training[, c(lon_name, lat_name)], types = c("double", "integer"))
x <- check_is_lat_lon(x)
if (length(lon_name) > 1) {
rlang::abort("`lon` should resolve to a single column name.")
}
check_type(training[, lon_name], types = c("double", "integer"))
if (length(lat_name) > 1) {
rlang::abort("`lat` should resolve to a single column name.")
}
check_type(training[, lat_name], types = c("double", "integer"))
if (any(names(training) == x$name)) {
rlang::abort("'", x$name, "' is already used in the data.")
}
step_geodist_new(
lon = x$lon,
lat = x$lat,
role = x$role,
trained = TRUE,
ref_lon = x$ref_lon,
ref_lat = x$ref_lat,
is_lat_lon = x$is_lat_lon,
log = x$log,
name = x$name,
columns = c(lat_name, lon_name),
skip = x$skip,
id = x$id
)
}
# TODO case weights for distances
geo_dist_calc_xy <- function(x_1, y_1, x_2, y_2) {
sqrt((x_1 - x_2)^2L + (y_1 - y_2)^2L)
}
# earth_radius = 6371e3 in meters
geo_dist_calc_lat_lon <- function(x_1, y_1, x_2, y_2, earth_radius = 6371e3,
call = caller_env()) {
if (any(abs(x_1) > 180.0)) {
rlang::abort("All `lon` values should be between -180 and 180", call = call)
}
if (any(abs(y_1) > 90.0)) {
rlang::abort("All `lat` values should be between -90 and 90", call = call)
}
to_rad <- pi / 180.0
y_1 <- y_1 * to_rad
y_2 <- y_2 * to_rad
x_1 <- x_1 * to_rad
x_2 <- x_2 * to_rad
delta_lat <- (y_2 - y_1) / 2.0
delta_lon <- (x_2 - x_1) / 2.0
a <- sin(delta_lat)^2L + cos(y_1) * cos(y_2) * sin(delta_lon)^2L
c <- 2.0 * atan2(sqrt(a), sqrt(1 - a))
earth_radius * c
}
#' @export
bake.step_geodist <- function(object, new_data, ...) {
check_new_data(names(object$columns), object, new_data)
object <- check_is_lat_lon(object)
if (object$is_lat_lon) {
dist_vals <-
geo_dist_calc_lat_lon(
new_data[[object$columns[2]]], # lon
new_data[[object$columns[1]]], # lat
object$ref_lon,
object$ref_lat
)
} else {
dist_vals <-
geo_dist_calc_xy(
new_data[[object$columns[2]]], # lon
new_data[[object$columns[1]]], # lat
object$ref_lon,
object$ref_lat
)
}
if (object$log) {
new_data[, object$name] <- log(dist_vals)
} else {
new_data[, object$name] <- dist_vals
}
new_data
}
print.step_geodist <-
function(x, width = max(20, options()$width - 30), ...) {
title <- paste(
"Geographical distances from",
format(x$ref_lat, digits = 10), "x",
format(x$ref_lon, digits = 10), "using "
)
print_step(x$columns, c(x$lat, x$lon), x$trained, title, width)
invisible(x)
}
#' @rdname tidy.recipe
#' @export
tidy.step_geodist <- function(x, ...) {
x <- check_is_lat_lon(x)
if (is_trained(x)) {
res <- tibble(
latitude = x$columns[1],
longitude = x$columns[2],
ref_latitude = x$ref_lat,
ref_longitude = x$ref_lon,
is_lat_lon = x$is_lat_lon,
name = x$name
)
} else {
res <- tibble(
latitude = sel2char(x$lat),
longitude = sel2char(x$lon),
ref_latitude = x$ref_lat,
ref_longitude = x$ref_lon,
is_lat_lon = x$is_lat_lon,
name = x$name
)
}
res$id <- x$id
res
}
|