[R-sig-Geo] Help on slow processing of extract fuction

Robert Hijmans r.hijmans at gmail.com
Tue Feb 22 22:35:24 CET 2011


> I have a classified image of whole India (India measures 3,214 km (1,997
mi) 
> from north to south and 2,993 km (1,860 mi) from east to west) at 56m 
> resolution. I have generate a square grid  of type polygon (area of each 
> square polygon in grid is 1sq km) that covers whole India. Now I have to 
> extract the fraction of crop classes from classified image for each square 
> polygon in the grid. 

Presumably you have the 1 km grid also as a raster file. I think I would do
this:

library(raster)
km <- raster("1km_raster_filename")
# make an "empty" RasterLayer
km <- raster(km)
# disaggregate to 50 m
m50 <- disaggregate(km, 20)

# resample land cover data to 50 m such that it lines up with the 1 km cells
you want.
x <- raster("land cover data file")

m50 <- resample(x, m50, method="ngb", filename="lc_resampled.tif",
progress="text")

# now things line up, and you could reclassify and use zonal to extract the
fraction of each class, but that would be a bit inefficient for what you
want. So I would do something along these lines

km1 <- writeStart(km, filename='km1.tif')
km2 <- writeStart(km, filename='km2.tif')

nsteps <- ceiling(nrow(km) / 20)
for (s in 1:nsteps) {
	r <- (s-1) * 20 + 1
	v <- getValues(m50, r, r + 19)
	# v has 20 rows of values. They need to be summarized in square blocks (20
columns)
	v <- matrix(as.vector(v), nrow=400)
	# % of values that is '1'
	vv1 <- apply(v, 2, fun(x) sum(x==1))  / 4
	km1 <- writeValues(km1, vv1, s)
	# % of values that is '2'
	vv2 <- apply(v, 2, fun(x) sum(x==2))  / 4
	km2 <- writeValues(km1, vv2, s)
}
km1 <- writeStop(km1)
km2 <- writeStop(km2)

# not tested, not dealing with NA values, and probably full of small errors,
so this will take some work, but I think the general approach should work.
See the rater vignette about writing functions for more details.

Hope this helps,
Robert
-- 
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Help-on-slow-processing-of-extract-fuction-tp6046528p6054157.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list