[R-sig-Geo] Spatial3dArray - coordinates method

Torleif Markussen Lunde torleif.lunde at cih.uib.no
Thu Nov 19 13:28:55 CET 2009


Hi

To read netcdf data (or any other "gridded" spatial time data) I find it 
convenient to define new classes Spatial3dArray and Spatial4dArray.

 setClass("Spatial3dArray", 
	  representation("Spatial", data = "array", coords = "list", 
			  time = "character", btime = "character"),
	  prototype= list(data = array(NA, c(1,1,1,1)), 
			  bbox=matrix(NA), 
			  proj4string = CRS(as.character(NA)), 
			  coords = list(1,1),
			  time = "posix",
			  btime = "posix"))


##########################################
###################EXAMPLE##################
##########################################

x <- matrix(seq(-10, 10, length = 100), 100, 100, 
	    byrow = FALSE)
y <- matrix(seq(-10, 10, length = 100), 100, 100, 
	    byrow = TRUE)

tm <- 1:10
tm.c <- as.character(seq(as.POSIXct("2002-01-01 06:00:00",
				    "2002-01-01 15:00:00"), 
			  by="hours", 
			  length.out=10))

z <- array(NA, c(dim(x)[1], dim(x)[2], length(tm.c), 1))

for (i in 1:10) {
z[,,i,] <- i * ( sin(sqrt(x^2+y^2)))
}

sin3dA <- new("Spatial3dArray", 
      data = z, 
      coords = list(x, y), 
      bbox = matrix(c(min(x), min(y), max(x), max(y), 2, 2), 2, 2, 
      dimnames = list(NULL, c("min","max"))), 
      time = tm.c,
      btime = c(min(tm.c), max(tm.c)))

dimnames(slot(sin3dA, "data")) = list(NULL, 
				      NULL, 
				      slot(sin3dA, "time"), 
				      c("a"))
names(slot(sin3dA, "coords")) <- c("x", "y")


##########################################

for the coordinates method I would like to have two options on how to return 
the coordinates; "list" or default "sp":

coordinates.3dArray <- function (obj, type = "sp") {	
	lat <- slot(obj, "coords")[[1]]
  	long <- slot(obj, "coords")[[2]]
  	if (type == "list") {
    		return(list(long=long, lat=lat))
    	} else if (type == "sp") {
		res <- as.matrix(cbind(c(long), c(lat)))
		dimnames(res) <- list(NULL, c("x1", "x2"))
	} 
}
setMethod("coordinates", signature("Spatial3dArray"), coordinates.3dArray)

This means that the default coordinates method in sp has to include the option 
"..." . Would it be possible to include this in a future release of sp? 

The reason I want to keep the list option is to use a matrix oriented approach 
in spplot, overlay, etc. methods. I also feel having a matrix/array approach 
with these kind of data makes sense. Allowing type = "sp" means overlay() will 
work more or less out of the box (however I would like to return a matrix), 
and still I could get the list/matrix when desired. 


Best wishes
Torleif Markussen Lunde
Centre for International Health
Bjerknes Centre for Climate Research
University of Bergen
Norway



More information about the R-sig-Geo mailing list