Goal

We create easy-to-understand R code for the creation of a variogram. To confirm that our code is correct, we compare the results with the output of the variogram function included in the gstat package. At the same time, this text hopefully helps the reader to improve his/her knowledge of the R language.

Overview

To make a variogram plot, the following steps are necessary:

Example data

We just invent some \((x, y)\) - coordinates where measurements of a some variable may have taken place. It should be clear from the beginning that 5 observations are far too little to create a meaningful variogram plot. However, 5 observations should be good enough to explain the principle.

x = c(0.1, -2.23, -0.5, 1.46, -1.46)
y = c(1.8, -2.14, 1.0, 2.27, 2.27)

We add some measurement data for the points, which are also purely fictional:

z = c(399.55, 427.19, 360.49, 376.66, 378.24)

It is convenient to collect the data in a data frame:

measurement = data.frame(x = x, y = y, z = z)
measurement
##       x     y      z
## 1  0.10  1.80 399.55
## 2 -2.23 -2.14 427.19
## 3 -0.50  1.00 360.49
## 4  1.46  2.27 376.66
## 5 -1.46  2.27 378.24

Let’s have a look at the locations:

maintxt = "Measurement points"
plot(measurement$x, measurement$y, col = "black", cex = 1.0, pch = 18, asp = 1,  
     xlab = "", ylab = "", main = maintxt, font.main = 1, ylim = c(-2.7, 2.7))
text(measurement$x, measurement$y, row.names(measurement), pos = 2, offset = 0.5)

Note: We set asp = 1 in the plot command. This forces the plot to an x:y aspect ratio of 1:1 which in turn allows us to estimate the relative distances of the points by eye.

It is essential for a variogram to know the mutual distances of all point pairs. The distances can be obtained using the dist command in R. The command calculates the Euclidian distance by default:

distances = dist(measurement[,1:2])  # Euclidian distance is default   
distances
##          1        2        3        4
## 2 4.577390                           
## 3 1.000000 3.585038                  
## 4 1.438923 5.750148 2.335487         
## 5 1.629264 4.476718 1.592011 2.920000

In general, there are \(n \cdot (n-1)/2\) pairwise distances for \(n\) points, so that we have 10 distances.

Note: Above, we supply only columns 1 and 2 of the data frame to the dist command, i. e. the coordinates only.
This is very important. If the whole data frame is supplied, the third column is considered as a 3rd coordinate, and 3-dimensional distances are calculated, completely distorting the results.

For those who do not trust the dist command, we check the distance between point 1 and point 5:

dx = x[5] - x[1]  
dy = y[5] - y[1]  
d = sqrt(dx^2 + dy^2)  # Pythagoras 
d
## [1] 1.629264

Binning according to the pairwise distances

The basic idea of a variogram is to subdivide the pairwise distances into groups (bins) according to their size. Roughly speaking, we just take all pairs of measurement points, and group them by how far apart they are.
Next, we estimate the variation in each group/bin by calculating the average squared difference between the measurement values (z) in that bin.

We start with the binning. Here, we decide to subdivide the mutual distances into 3 bins (small distances, medium distances, large distances):

numBins = 3   # our decision 

If we want 3 bins, we have to find 4 margins (breaks). We just use seq in R to accomplish this:

breaks <- seq(0, max(distances), length.out = numBins + 1) 
breaks
## [1] 0.000000 1.916716 3.833432 5.750148

Consequently, we sudivide the pairwise differences into 3 size groups:

Note: It is questionable if we should start the leftmost bin with 0, because the first bins might end up empty (if we don’t have small distances). But we will stick to it because gstat::variogram does so, and we want to compare the results to confirm that we have understood the algorithm.

We can check if the breaks are equally spaced using diff:

diff(breaks)  # distance between the boundaries (breaks, borders)
## [1] 1.916716 1.916716 1.916716

Note: It is not mandatory to use equally spaced breaks. We can for example create breaks so that we have equal numbers of distances in each bin or define a grid that is closely knit at small distances and coarser elsewhere.

Now, we have to find out which point pair belongs to which bin. We obtain all pairs with the combn function:

n = nrow(measurement)                         # number of measurement points 
numPairs = n*(n-1)/2                          # number of pairs for n items 
pairs = combn(1:n, 2)                         # all combinations of the numbers 1 to 5
colnames(pairs) = paste0("pair", 1:numPairs)  # add some coumn names
rownames(pairs) = c("i", "j")                 # add row names 
pairs
##   pair1 pair2 pair3 pair4 pair5 pair6 pair7 pair8 pair9 pair10
## i     1     1     1     1     2     2     2     3     3      4
## j     2     3     4     5     3     4     5     4     5      5

Let’s note here the following (we will need this below): We can, for instance, access the x-coordinates of pair 3 (including point 1 and point 4) by the following code:

measurement$x[c(pairs[,3])] # x-coordinates of pair 3
## [1] 0.10 1.46

Check this in the measurement data frame above. The y-coordinates are.

measurement$y[c(pairs[,3])] # y-coordinates of pair 3
## [1] 1.80 2.27

It is cruicial to correctly assign the distances (the output of dist) to the point pairs (in the pairs array). The following code shows that the values in the dist object are orded column-wise, i.e. 1-2, 1-3, 1-4,…
This is the same order as in the pairs object above.

distances
##          1        2        3        4
## 2 4.577390                           
## 3 1.000000 3.585038                  
## 4 1.438923 5.750148 2.335487         
## 5 1.629264 4.476718 1.592011 2.920000
as.numeric(distances)  # watch the order by comapring with the 'distances' object!
##  [1] 4.577390 1.000000 1.438923 1.629264 3.585038 5.750148 4.476718 2.335487
##  [9] 1.592011 2.920000

Hence we can stay calm and use the cut command to find out which points pair belongs to which distance bin:

groups = as.integer(cut(as.numeric(distances), breaks = breaks)) 
groups 
##  [1] 3 1 1 1 2 3 3 2 1 2

That means the (distance of the) first pair belongs to bin 3, the next 3 pairs belong to bin 1, the next pair to bin 2, etc.

We will collect this knowledge in a list (the elements of a list can have different length which is necessary here):

group_index = list()
for (i in 1:numBins) {
  group_index[[i]] = which(groups == i)
}
group_index
## [[1]]
## [1] 2 3 4 9
## 
## [[2]]
## [1]  5  8 10
## 
## [[3]]
## [1] 1 6 7

Having this list, we can for instance find all distances in bin 1 using:

group_index[[1]] 
## [1] 2 3 4 9

A graph with connecting lines

We will now plot the graph of the measurement points again, but will connect the point pairs with lines. The trick is that we colour the connecting lines according to the distance bin they belong to:

colvec = rep(NA, ncol(pairs))       # initialize the colour vector with NA
colvec[group_index[[1]]] = "red"    # paint all pairs in group 1 red
colvec[group_index[[2]]] = "green"  # paint all pairs in group 2 green
colvec[group_index[[3]]] = "blue"   # paint all pairs in group 3 blue
sum(is.na(colvec)) == 0             # everything painted ?
## [1] TRUE
colvec
##  [1] "blue"  "red"   "red"   "red"   "green" "blue"  "blue"  "green" "red"  
## [10] "green"

We resume the plot with the points and add the connecting lines afterwards:

maintxt = "Edges grouped by length"
plot(measurement$x, measurement$y, col = "black", cex = 1.0, pch = 18, asp = 1,  
     xlab = "", ylab = "", main = maintxt, font.main = 1, ylim = c(-2.7, 2.7))

# numbers, subtext:
text(measurement$x, measurement$y, row.names(measurement), pos = 2, offset = 0.5)
mtext("Colour indicates spatial separation of the point pairs", cex = 0.9, col = "blue")

# connecting lines:
for (i in 1:ncol(pairs)) {
  lines(measurement$x[c(pairs[,i])], measurement$y[c(pairs[,i])], col = colvec[i])
}

# legend:
leg1 = paste(round(breaks[1], 2), "< distance <=", round(breaks[2],2))
leg2 = paste(round(breaks[2], 2), "< distance <=", round(breaks[3],2))
leg3 = paste(round(breaks[3], 2), "< distance <=", round(breaks[4],2))
legend_text = c(leg1, leg2, leg3)
legend("bottomright", legend_text, col = c("red", "green", "blue"), lwd = 2, cex = 0.9)

According to our binning procedure above, the red lines should be the shortest, the green lines should have a medium length, and the blue lines should be the longest. It seems that this is true.

Calculation of the semivariance \(\gamma(h)\)

We continue with the estimation of the variation of the measurement values (\(z\)) in each bin. In our case, this means that we want to know how large the variation is over short, medium, and large distances.
The average of the squared differences between the pairs - called semivariance (\(\gamma\)) - can be used as such a measure for the variation.

The spatial correlation can be modelled using the expectation value of the squared differences of the obervations separated by a distance \(h\), i.e. \(\gamma(h) = 1/2 \cdot \mathbb{E} \{ [Z(s)−Z(s+h)]^2\}\). If we unravel the expectation \(\mathbb{E}\), we get:

\[ \gamma(h) = \frac{1}{2 \cdot N(h)} \cdot \sum_s \left( Z(s) - Z(s+h) \right)^2 \]

(So, “expectation value” means nothing but the average here!)

The factor of \(1/2\) is there for convenience (see Appendix).
In the formula above, the sum goes over all pairs \(s\) having the same separation \(h\), and \(N(h)\) is their count.

This formula is not practically applicable because it is very unlikely that several pairs of observations have the same spatial distance \(h\). Consequently, \(h\) is seen as the mean of all pairwise distances embraced in the same bin. The above formula is therefore replaced by its sample estimator:

\[ \gamma_{bin} = \frac{1}{2 \, N_{bin}} \sum\limits_{\text{all pairs}} \big[ \ z(i) - z(j) \ \big]^2 \]

This means that we replace the uniform distance \(h\) by the slightly varying distances of the observations collected in the same bin. This should not result in a large deviation from the exact expression if the bin is not too wide.

The symbols in the formula above mean:

The sum is over all pairs in a bin , not over individual measurements. In our case, we have 4 terms for bin 1 (smallest distance), and 3 terms for bin 2 and bin 3 (medium and large distances, respectively). Each term in the sum is the squared difference of the two measurements belonging to one pair in the same bin.

We have 3 bins, so we get 3 \(\gamma\)-values (if all bins are non-empty). We initialize vectors to store the \(\gamma\)-values and the number of pairs in the individual bins:

gamma = rep(NA, numBins) 
N = rep(NA, numBins)

In order to explain the calculation in detail, we carry out the computation for each bin seperately.

Bin 1

i = 1
binIndices = group_index[[i]]  # the indices for group i (regarding the pairs object)
binIndices
## [1] 2 3 4 9
binPairs = pairs[,binIndices]  # the pairs in that bin
binPairs
##   pair2 pair3 pair4 pair9
## i     1     1     1     3
## j     3     4     5     5
N[i] = length(binIndices)         # the number of pairs in that bin 
N[i]
## [1] 4
gamma[i] = 0.5/N[i] * ((z[1] - z[3])^2 + (z[1] - z[4])^2  + (z[1] - z[5])^2 + (z[3] - z[5])^2)  # sum over pairs (see binPairs)

The code calculates

\[ \gamma_1 = \frac{1}{2 \cdot 4} \big[ (z_1 - z_3)^2 + (z_1 - z_4)^2 + (z_1 - z_5)^2 + (z_3 - z_5)^2 \big] \]

Bin 2

i = 2
binIndices = group_index[[i]]  # the indices for group i (regarding the pairs object)
binIndices
## [1]  5  8 10
binPairs = pairs[,binIndices]  # the pairs in that bin
binPairs
##   pair5 pair8 pair10
## i     2     3      4
## j     3     4      5
N[i] = length(binIndices)         # the number of pairs in that bin 
N[i] 
## [1] 3
gamma[i] = 0.5/N[i]  * ((z[2] - z[3])^2 + (z[3] - z[4])^2  + (z[4] - z[5])^2)   # sum over pairs (see binPairs)

The code calculates

\[ \gamma_2 = \frac{1}{2 \cdot 3} \big[ (z_2 - z_3)^2 + (z_3 - z_4)^2 + (z_4 - z_5)^2 \big] \]

Bin 3

i = 3
binIndices = group_index[[i]]  # the indices for group i (regarding the pairs object)
binIndices
## [1] 1 6 7
binPairs = pairs[,binIndices]  # the pairs in that bin
binPairs
##   pair1 pair6 pair7
## i     1     2     2
## j     2     4     5
N[i] = length(binIndices)         # the number of pairs in that bin 
N[i] 
## [1] 3
gamma[i] = 0.5/N[i]  * ((z[1] - z[2])^2 + (z[2] - z[4])^2 + (z[2] - z[5])^2)   # sum over pairs (see binPairs)

The code calculates

\[ \gamma_3 = \frac{1}{2 \cdot 3} \big[ (z_1 - z_2)^2 + (z_2 - z_4)^2 + (z_2 - z_5)^2 \big] \]

In the above formulas, each pair is counted once, and each pair belongs to exactly one bin (bins are disjoint).

Here are the calculated semivariances:

gamma
## [1] 352.3518 785.4759 952.2255

The variogram plot

The \(\gamma\)-values are usually plotted as a function of the mean distances of the bins:

meanDistance = rep(NA, numBins)  # initialise with NA  
for (i in 1:numBins) {
  meanDistance[i] = mean(distances[group_index[[i]]])  
}
meanDistance
## [1] 1.415050 2.946842 4.934752

We are now ready to have a look at the variogram plot:

plot(meanDistance, gamma, pch = 18, col = "blue", cex = 1.8, type = "b", lty = 2,
     xlab = "h", ylab = bquote(gamma), cex.lab = 2, main = "Variogram", font.main = 1, cex.main = 1.7)

We mentioned already that we cannot create a meaningful (and nice) variogram from 5 data points in 3 bins. At least resembles the plot what we expect from a variogram. What we expect is a curve that starts with low variation for small distances and shows larger variation for larger distances. Imagine you are in a landscape and measure the elevation in a certain area. If the area is small (small distances!), you expect also small variation. If you widen the area of observation, a few valleys and a few additional hills might come into play, increasing the variation. The wider your area, the larger the variation. However, if you look at very large areas/distances, you sooner or later include some sea-level beach and the Mount Everest, so that even more expansion of the observation area does not result in even higher variance: the variance saturates at very large distances. So what we expect is something like that:

In another text, we are going to use better data in order to get a better variogram.

Summary of the results

We collect the results in a data frame:

results_df <- data.frame(Nbin = N, dist = meanDistance, gamma = gamma)
results_df
##   Nbin     dist    gamma
## 1    4 1.415050 352.3518
## 2    3 2.946842 785.4759
## 3    3 4.934752 952.2255

Here, each row contains data for one bin. Nbin is the number of distance pairs in a bin. The column dist contains the mean spatial (Euclidian) distance of pairs in that bin. The gamma-column displays the calculated semi-variance.

In a follow-up of this text, we present a simple function for the creation of a variogram and compare its results with the output of the variogram function of the gstat library.



Mail to Uwe Menzel