Skip to content

Instantly share code, notes, and snippets.

@bbolker
Forked from mikebirdgeneau/3d_kriging_cgs.R
Created February 25, 2025 16:26
Show Gist options
  • Save bbolker/2b7c81deb3f92a03e64a4656a8c62fe1 to your computer and use it in GitHub Desktop.
Save bbolker/2b7c81deb3f92a03e64a4656a8c62fe1 to your computer and use it in GitHub Desktop.
3D Kriging with Conditional Gaussian Simulation in R
library(gstat)
library(lattice)
# Create Data Points (Random)
n <- 50
data3D <- data.frame(x = runif(n), y = runif(n), z = runif(n), v = rnorm(n))
coordinates(data3D) = ~x+y+z
# Create empty grid to krige
range1D <- seq(from = 0, to = 1, length = 20)
grid3D <- expand.grid(x = range1D, y = range1D, z = range1D)
gridded(grid3D) = ~x+y+z
# Perform CGS with 10 realizations; maxdist & nmax important for speed of calculation.
res3D <- krige(formula = v ~ 1, data3D, grid3D, model = vgm(1, "Exp", .2),nsim=10,maxdist=10,nmax=9)
# Plot Results
levelplot(sim1 ~ x + y | z, as.data.frame(res3D))
@bbolker
Copy link
Author

bbolker commented Feb 25, 2025

Modified version 2025: add sp() package, show ordinary kriging, finer x/y grid

library(gstat)
library(lattice)
library(sp)

# Create Data Points (Random)
n <- 50
data3D <- data.frame(x = runif(n), y = runif(n), z = runif(n), v = rnorm(n))
coordinates(data3D) <- ~x+y+z

# Create empty grid to krige
range1D <- seq(from = 0, to = 1, length = 51)
rangez <- seq(from = 0, to = 1, length = 25)
grid3D <- expand.grid(x = range1D, y = range1D, z = rangez)
gridded(grid3D) = ~x+y+z

# Perform CGS with 10 realizations; maxdist & nmax important for speed of calculation.
res3D <- krige(formula = v ~ 1, data3D, grid3D,
               model = vgm(1, "Exp", .2),nsim=10,maxdist=10,nmax=9)

## ordinary kriging
res3Dx <- krige(formula = v ~ 1, data3D, grid3D,
               model = vgm(1, "Exp", .2),maxdist=10,nmax=9)

# Plot Results
levelplot(var1.pred ~ x + y | z, as.data.frame(res3Dx),
          useRaster = TRUE)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment