Back to news

R Package Tutorial

SingRegKrig: A Complete R Tutorial for Singularity Regression Kriging

From data preparation and model fitting to spatial cross-validation, uncertainty mapping, and reproducible prediction.

SingRegKrig package cover showing singularity features, random forest regression, and ordinary kriging
Date
Package
SingRegKrig 0.1.0
Language
R
Workflow
End-to-end spatial prediction
Official R package SingRegKrig Version 0.1.0 https://CRAN.R-project.org/package=SingRegKrig Developers Shikhar Tyagi, Arvind Pandey, Bhupendra Singh, and Vrijesh Tripathi Maintainer Shikhar Tyagi Open CRAN

What this tutorial covers

From heterogeneous covariates to a validated spatial prediction

Environmental relationships are often nonlinear, non-stationary, and affected by local anomalies. Singularity Regression Kriging (SRK) addresses this setting by combining multi-scale singularity features, a random-forest trend, and ordinary kriging of the remaining residuals.

Environmental covariates Multi-scale singularity Random-forest trend Residual kriging Final prediction

Before you begin

Package, files, and source material

The worked example is self-contained: sim_srk_data() generates the tutorial data in R, so no external input file is required. When adapting the workflow to a real study, prepare one sample file and one prediction-grid file with matching coordinate and covariate fields.

R package SingRegKrig 0.1.0 Install from CRAN
Observed samples sample_data.csv Target, coordinates, and covariates
Prediction grid prediction_grid.csv Coordinates and matching covariates
Model output SingRegKrig_predictions.csv Predictions, trend, residual, and uncertainty

This tutorial follows version 0.1.0 and uses the supplied cover, package logo, and twelve reproducible result figures.

Original method paper

Ren, K., Song, Y.*, Chen, M., & Yu, Q. (2026). “A singularity regression kriging for spatial prediction.” GIScience & Remote Sensing, 63(1), 2690341.

01

Set up R

Install the package and fix the random seed

Install the package once, then load the two libraries used throughout this walkthrough.

install.packages("SingRegKrig")

library(SingRegKrig)
library(ggplot2)

set.seed(42)
packageVersion("SingRegKrig")
# [1] '0.1.0'
Reproducibility note

Record the R version, package version, and random seed in every formal analysis.

02

Prepare the data

Build and inspect a skewed spatial dataset

An SRK analysis needs four types of information.

Field typeExamplePurpose
ResponsezObserved target at sampled locations
Coordinatesx, yProjected coordinates, normally in metres
Covariatescov1, elevation, slopeRequired at samples and prediction locations
Prediction locationsMatching coordinates and covariatesNo response field is required
tutorial_data <- sim_srk_data(
  n_side = 20,
  scenario = "skewed",
  seed = 42
)

dim(tutorial_data)
# [1] 400   4

head(tutorial_data, 8)
summary(tutorial_data)

The result contains 400 locations and four fields: x and y are coordinates, z is the response, and cov1 is the environmental covariate. There are no missing or non-finite values.

Keep units consistent

Do not mix longitude and latitude in degrees with analysis scales in metres. If the singularity scales are 2,000–20,000 m, use a projected coordinate system measured in metres.

03

Explore first

Check spatial patterns, skewness, and covariate relationships

Before fitting a model, inspect the response and covariate maps, the response distribution, and the shape of the covariate–response relationship.

spatial_long <- rbind(
  data.frame(x = tutorial_data$x, y = tutorial_data$y,
             variable = "Response z", value = tutorial_data$z),
  data.frame(x = tutorial_data$x, y = tutorial_data$y,
             variable = "Covariate cov1", value = tutorial_data$cov1)
)

ggplot(spatial_long, aes(x, y, fill = value)) +
  geom_raster() +
  coord_equal() +
  facet_wrap(~variable) +
  scale_fill_viridis_c() +
  theme(panel.grid = element_blank())
Spatial maps of response z and covariate cov1
Figure 1 Spatial patterns of the response and environmental covariate.
Histogram and density curve of the response variable
Figure 2 The response is clearly right-skewed.
Scatter plot and smooth curve showing the relationship between cov1 and z
Figure 3 The covariate–response relationship is associated but not fully linear.

This combination of spatial structure, skewness, and nonlinearity is precisely where a random-forest trend and multi-scale singularity features may add useful information.

04

Engineer spatial features

Compute and interpret the singularity index

In two dimensions, an index near 2 indicates locally uniform behaviour; values below 2 indicate local enrichment or a positive anomaly; and values above 2 indicate local depletion. Because the simulated grid spacing is 1, this example uses scales from 1 to 5 grid units.

coords <- tutorial_data[c("x", "y")]

alpha_cov1 <- compute_singularity(
  coords = coords,
  values = tutorial_data$cov1,
  scales = 1:5,
  min_neighbours = 3,
  min_scales = 2
)

summary(alpha_cov1)
sd(alpha_cov1)
# Mean: 2.039; SD: 0.2482
Map of the singularity index for cov1
Figure 4 Low values show local enrichment; high values show local depletion.

Whether a singularity feature enters the final trend model also depends on sd_threshold. Features with very little variation are removed automatically so that near-constant inputs do not add noise to the random forest.

05

Design a realistic test

Create a continuous spatial holdout

Hide the central 8 × 8 block from model fitting. The outer 336 locations become training samples and the central 64 locations form a contiguous, unsampled prediction area.

holdout_index <- with(
  tutorial_data,
  x >= 7 & x <= 14 & y >= 7 & y <= 14
)

train_data <- tutorial_data[!holdout_index, ]
test_data  <- tutorial_data[holdout_index, ]

c(training = nrow(train_data), holdout = nrow(test_data))
# training holdout
#      336      64
Map of training samples around a central spatial holdout block
Figure 5 Training samples surround a completely hidden central prediction block.

A contiguous holdout is closer to predicting an unsampled area than a random split, and it reduces the spatial leakage caused by placing neighbouring observations in both training and test sets.

06

Fit the model

Run singularity regression kriging

set.seed(42)

srk_model <- srk(
  z ~ cov1,
  data = train_data,
  coords = ~x + y,
  pred_data = test_data,
  scales = 1:5,
  ntree = 300,
  sd_threshold = 0.10,
  min_neighbours = 3,
  min_scales = 2,
  variogram_model = "auto"
)

print(srk_model)
scales = 1:5Spatial scales used to compute singularity features
ntree = 300Number of trees in the random forest
sd_threshold = 0.10Standard-deviation filter for singularity features
variogram_model = "auto"Automatic choice among spherical, exponential, and Gaussian models
Training observations336
Retained featuresv_cov1
Training R²0.9516
Training RMSE0.1340
Training MAE0.0948
srk_model$retained_features
# [1] "sv_cov1"

unlist(srk_model$metrics)
#      R2    RMSE     MAE
# 0.95156 0.13402 0.09479

srk_model$variogram_model
#   model    psill range
# 1   Nug 0.011243 0.000
# 2   Exp 0.007597 2.562

sort(srk_model$feature_importance, decreasing = TRUE)
#    cov1 sv_cov1
#   87.11   15.42
Training fit is not predictive accuracy

These metrics describe the in-sample random-forest trend. Use the independent holdout and spatial block cross-validation results below for performance claims.

07

Diagnose the model

Inspect residuals, importance, fit, and the variogram

plot(srk_model, which = 1:4)
Four SRK diagnostic plots showing residuals, importance, fitted values, and variogram
Figure 6 SRK model diagnostics in one view.
  • Residuals should remain centred near zero without a strong systematic shift.
  • Variable importance shows the contributions of raw and singularity features.
  • Observed and fitted values should approach the 1:1 line.
  • The variogram describes residual spatial dependence used by ordinary kriging.
08

Read the output

Separate the trend, kriged residual, and uncertainty

Because pred_data was supplied during fitting, the holdout predictions are already stored in srk_model$predictions. The same result can be regenerated explicitly with predict(srk_model, newdata = test_data).

ColumnMeaning
x, yPrediction-location coordinates
predictionFinal SRK prediction
trendRandom-forest trend prediction
kriged_residualOrdinary-kriging interpolation of the residual
kriging_seStandard error of residual kriging
head(srk_model$predictions)

identity_error <- max(abs(
  srk_model$predictions$prediction -
    srk_model$predictions$trend -
    srk_model$predictions$kriged_residual
))

identity_error
# [1] 1.041e-16
Final prediction = random-forest trend + kriged residual

The near-zero identity error confirms the decomposition. Note that kriging_se captures uncertainty in residual kriging only; it does not include uncertainty from the random-forest trend and should not be presented as a complete prediction interval.

09

Map and validate

Evaluate the continuous holdout area

Observed, predicted, error, and kriging uncertainty maps for the holdout area
Figure 7 Observed values, predictions, errors, and residual-kriging uncertainty.

The observed and predicted panels share a colour scale. In the error panel, red indicates overprediction and blue indicates underprediction; the final panel shows the spatial pattern of kriging standard error.

observed <- test_data$z
predicted <- srk_model$predictions$prediction

holdout_metrics <- data.frame(
  n = sum(complete.cases(observed, predicted)),
  R2 = cor(observed, predicted, use = "complete.obs")^2,
  RMSE = sqrt(mean((predicted - observed)^2, na.rm = TRUE)),
  MAE = mean(abs(predicted - observed), na.rm = TRUE)
)

holdout_metrics
#    n     R2   RMSE    MAE
# 1 64 0.6167 0.1968 0.1419
Observed versus predicted values in the spatial holdout coloured by kriging uncertainty
Figure 8 Observed versus predicted values for the 64 hidden locations.
Holdout R²0.6167
Holdout RMSE0.1968
Holdout MAE0.1419

This test measures interpolation into a contiguous unsampled patch surrounded by training observations; it does not evaluate extrapolation beyond the study boundary.

10

Strengthen validation

Run five-fold spatial block cross-validation

A single holdout may depend on where it is placed. Spatial block cross-validation keeps neighbouring locations together and assigns entire blocks to folds, reducing optimistic leakage between train and test data.

set.seed(42)

cv_result <- srk_block_cv(
  z ~ cov1,
  data = tutorial_data,
  coords = ~x + y,
  nfold = 5,
  block_size = 4,
  scales = 1:5,
  ntree = 200,
  sd_threshold = 0.10
)

print(cv_result)
cv_result$fold_metrics
unlist(cv_result$overall_metrics)
Overall R²0.8220
Overall RMSE0.2458
Overall MAE0.1812
Map of the five spatial cross-validation folds
Figure 9 Spatially contiguous fold assignment.
Observed versus cross-validated predictions coloured by fold
Figure 10 Observed versus spatially cross-validated predictions.
Map of spatial cross-validation prediction errors
Figure 11 Spatial distribution of cross-validation errors.

Inspect both per-fold and overall metrics. The fold map confirms that validation blocks are spatially coherent, while the error map reveals areas with persistent over- or underprediction.

11

Test robustness

Compare scales and screening thresholds

For a quick sensitivity experiment, use a smaller 12 × 12 dataset and compare nine combinations of maximum scale and singularity-feature threshold.

sensitivity_data <- sim_srk_data(
  n_side = 12,
  scenario = "skewed",
  seed = 42
)

set.seed(42)

sensitivity_result <- srk_sensitivity(
  z ~ cov1,
  data = sensitivity_data,
  coords = ~x + y,
  scale_range = c(3, 5, 7),
  threshold_range = c(0, 0.10, 0.30),
  nfold = 3,
  block_size = 4,
  ntree = 100,
  scale_step = 1
)

print(sensitivity_result)

par(mfrow = c(1, 3))
plot(sensitivity_result, metric = "R2")
plot(sensitivity_result, metric = "RMSE")
plot(sensitivity_result, metric = "MAE")
Sensitivity plots for R squared, RMSE, and MAE across maximum scale and threshold settings
Figure 12 Parameter sensitivity across maximum scale and feature threshold.

Do not select a setting from the single highest R² alone. Look for stable performance across neighbouring combinations and favour parameters that match the scientific process scale and computational budget.

Version 0.1.0 behaviour

The sensitivity function creates a new random spatial fold assignment for each parameter combination. For a formal comparison, predefine one fold scheme and reuse it across all settings.

12

Move to a real study

Adapt the workflow to your own files

In this template, the sample file contains target, projected coordinates, and three environmental covariates. The prediction grid contains the same coordinate and covariate fields but no target.

sample_data <- read.csv("sample_data.csv")
prediction_grid <- read.csv("prediction_grid.csv")

required_sample_columns <- c(
  "target", "x", "y", "elevation", "slope", "covariate2"
)
required_grid_columns <- c(
  "x", "y", "elevation", "slope", "covariate2"
)

stopifnot(all(required_sample_columns %in% names(sample_data)))
stopifnot(all(required_grid_columns %in% names(prediction_grid)))

set.seed(42)

my_model <- srk(
  target ~ elevation + slope + covariate2,
  data = sample_data,
  coords = ~x + y,
  pred_data = prediction_grid,
  scales = seq(2000, 20000, 2000),
  ntree = 500,
  sd_threshold = 0.5,
  min_neighbours = 3,
  min_scales = 2,
  variogram_model = "auto"
)

print(my_model)
summary(my_model)
head(my_model$predictions)

write.csv(
  my_model$predictions,
  "SingRegKrig_predictions.csv",
  row.names = FALSE
)
13

Final checks

Seven details that determine whether the result is credible

  1. Specify scales explicitly. Base them on sampling density, process scale, and coordinate units.
  2. Inspect retained features. An empty retained_features object means no singularity feature entered the trend model.
  3. Separate fit from validation. Report spatial holdout or block-CV metrics, not only model$metrics.
  4. Fix the random seed. Random forests and spatial fold allocation both include random processes.
  5. Predict the complete grid together. Version 0.1.0 computes singularity from the training locations and the supplied newdata; avoid arbitrary batches.
  6. Interpret uncertainty precisely. kriging_se is residual-kriging uncertainty, not a complete prediction interval.
  7. Estimate the computational load. Test a subset before running multi-scale neighbourhood searches on very large grids.

Closing note

A concise interface still requires rigorous spatial reasoning

A successful function call is only the beginning. Credible SRK results depend on informative covariates, compatible coordinates and scales, retained singularity features, a defensible residual variogram, strict spatial validation, and careful uncertainty interpretation.

Run the simulated example first, then replace the response, coordinates, covariates, and grid with your own data.

SingRegKrig logo
Citation

Ren, K., Song, Y.*, Chen, M., & Yu, Q. (2026). “A singularity regression kriging for spatial prediction.” GIScience & Remote Sensing, 63(1), 2690341. https://doi.org/10.1080/15481603.2026.2690341