[R-sig-Geo] Calculating/applying transition matrices from classified imagery?

Robert Hijmans r.hijmans at gmail.com
Tue Apr 12 22:07:52 CEST 2011

> Does anyone know of a package (or a suggestion on how to implement) to 
> calculate, for two classified raster images of the same location but 
> different times, the relative probability of transitioning from one class
> to 
> the other?  Additionally, once this is figured out, how to apply this 
> transition matrix the one of the rasters to predict future per-class 
> probabilities?  Thanks!  Ideally this should support arbitrarily large 
> files. 
> --j 


Is the below what you are after? Perhaps there are some Markov chain
implementations that could provide additional things.


# creating two classified rasters
s <- r <- raster(nrow=10, ncol=10)
r[] <- rep(1:5, each=20)
s[] = round(r[] + rnorm(ncell(r), sd=0.5))
s[s<1] <- 1
s[s>5] <- 5

# cross tabulate to get probabilities of transition
crt <- crosstab(r, s)
crt <- crt / apply(crt, 1, sum) # probabilities

# function to apply the cross tab probs
fun <- function(x) {
	classes <- as.numeric(rownames(crt))
	res <- matrix(nrow=length(x), ncol=ncol(crt))
	for (i in 1:length(classes)) {
		tr <- t(res[x==classes[i], ])
		tr[] <- crt[i,]
		res[x==classes[i], ] <- t(tr)

x <- calc(s,fun=fun)
layerNames(x) <- paste('p( x =', 1:5, ')')

plot(r, main='first')
plot(s, main='second')

View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Calculating-applying-transition-matrices-from-classified-imagery-tp6247825p6266539.html
Sent from the R-sig-geo mailing list archive at Nabble.com.

More information about the R-sig-Geo mailing list