10

There are 100 SpatialPointsDataFrames in my Workspace. I loaded them on this way:

filenames <- list.files(path="",
                        pattern="XYhectareTravelTimes_ez+.*shp")

for(i in filenames){
              filepath <- file.path("/",i)
              assign(i, readShapePoints(filepath))

They are called like this:

XYhectareTravelTimes_ez10.*shp 
XYhectareTravelTimes_ez11.*shp 
XYhectareTravelTimes_ez12.*shp 

etc.

How can I convert them to rasters looping through the Workspace?

I am very new R user and hoping to find some help. thanks a lot.

whuber
  • 69,783
  • 15
  • 186
  • 281
Trident
  • 101
  • 1
  • 1
  • 3

2 Answers2

11

If your data contains xyz data (where z is the raster value) and your points are on a regular grid (no need for interpolation).

library("raster")
r <- rasterFromXYZ(as.data.frame(travel)[, c("x", "y", "z")])

If you need interpolation, you can use akima library :

library("raster")
library("akima")

steps <- 100
isu <- with(travel@data, interp(x, y, z, 
    xo=seq(min(x), max(x), length = steps),
    yo=seq(min(y), max(y), length = steps)
))

r <- raster(isu)

Now, to do this sequentially you just need to wrap it in a for loop (I've tried to stay as close as possible from the information you gave in your question) :

library("raster")

filenames <- list.files(path="", pattern="XYhectareTravelTimes_ez+.*shp")

# create a container for all the rasters
raster_cat <- list()

for (i in filenames) { 
  travel <- readShapePoints(i)
  r <- rasterFromXYZ(as.data.frame(travel)[, c("x", "y", "z")])
  raster_cat[[i]] <- r
}
Etienne Racine
  • 416
  • 4
  • 9
  • I'd advice against using travel@data (or using @ at all), as this relies on the internal names of a SpatialPointsDataFrame, which might change. I suggest using as.data.frame, which does not rely on these internal names. – Paul Hiemstra Oct 15 '12 at 21:04
  • Good point. I've changed it. I like the slot usage because it's more compact, but you're right. – Etienne Racine Oct 16 '12 at 14:09
6

In addition to @Etiennebr's answer, I'd go for an apply style loop (which is more R-ish, and uses less code for the same thing):

library("raster")

filenames <- list.files(path="", pattern="XYhectareTravelTimes_ez+.*shp")

raster_cat = lapply(filenames, function(x) {
  travel <- as.data.frame(readShapePoints(x))
  r <- rasterFromXYZ(travel[, c("x", "y", "z")])
})
Paul Hiemstra
  • 1,051
  • 6
  • 9
  • Hoi Paul, thank you very much for the answer!! Your method is much easyer than the one I figured out. If you are interested in my methode just let me know. Best regards, Livia –  Jan 30 '13 at 14:33