fit_local_rf: Fit one local random forest

View source: R/fit_local_rf.R

fit_local_rfR Documentation

Fit one local random forest

Description

Fit one local random forest

Usage

fit_local_rf(
  data,
  formula,
  coords,
  focal_index,
  bandwidth,
  adaptive = TRUE,
  kernel = "bisquare",
  num.trees = 500,
  mtry = NULL,
  min.node.size = 5,
  importance = "permutation",
  use_case_weights = TRUE,
  seed = NULL,
  keep_model = FALSE,
  neighbor_unit = "row",
  location_id = NULL
)

Arguments

data

Data frame containing response and predictors.

formula

Model formula.

coords

Numeric matrix/data frame with 2 columns.

focal_index

Integer index of the focal observation.

bandwidth

Adaptive k or fixed distance threshold.

adaptive

Logical; adaptive or fixed neighborhood.

kernel

Kernel type.

num.trees

Number of trees for ranger.

mtry

Number of variables tried at each split.

min.node.size

Minimum node size for ranger.

importance

Importance type passed to ranger.

use_case_weights

Logical; whether to pass kernel weights to ranger.

seed

Optional random seed.

keep_model

Logical; whether to retain fitted ranger model.

neighbor_unit

Character string indicating whether neighborhoods are defined using individual data rows ("row") or unique spatial locations ("location").

location_id

Optional vector identifying the spatial location associated with each observation. Required when neighbor_unit = "location".

Value

A named list containing the results for one focal local random forest:

focal_index

Integer index of the focal observation.

observed

Observed response value at the focal observation.

prediction

Prediction from the local random forest for the focal observation.

residual

Observed minus predicted response for the focal observation.

n_local

Number of complete observations used to fit the local random forest.

local_bandwidth

Realized spatial bandwidth of the local neighborhood.

variable_importance

Named numeric vector of local variable importance values, or NA when importance cannot be calculated.

ranger_model

The fitted ranger model when keep_model = TRUE; otherwise NULL.

Examples

set.seed(1)

n <- 20
dat <- data.frame(
  y = rnorm(n),
  x1 = rnorm(n),
  x2 = runif(n)
)
coords <- cbind(seq_len(n), rep(0, n))

local_fit <- fit_local_rf(
  data = dat,
  formula = y ~ x1 + x2,
  coords = coords,
  focal_index = 10,
  bandwidth = 12,
  adaptive = TRUE,
  num.trees = 10,
  seed = 1
)

local_fit$prediction

gwrf documentation built on Aug. 24, 2026, 5:15 p.m.