Search code examples
rraster

R: Create raster object from a dataframe with min and max values for x and y coordinates of raster cells


I have a dataframe that containts minimum and maximum values for x and y coordinates of raster cells. it starts like this:

          xmin      ymin      ymax      xmax
   1 -73.99139 -18.04158 -17.04158 -72.99139
   2 -72.99139 -18.04158 -17.04158 -71.99139
   3 -71.99139 -18.04158 -17.04158 -70.99139
   4 -70.99139 -18.04158 -17.04158 -69.99139
   5 -69.99139 -18.04158 -17.04158 -68.99139
   6 -68.99139 -18.04158 -17.04158 -67.99139

and goes on for ~800 rows where each row represents one raster cell

It seems that the raster function from the raster package allows for setting xmn as the minimum x coordinate (left border) as well as xmx and ymn and ymx. However this is with regard to a raster extent for the whole rastr object itself... not a single cell.

How can I create a raster object with theses single cell values?


Solution

  • How about something like this...

    when df is your dataframe with the minimum and maximum values:

           xmin      ymin      ymax      xmax
    1 -73.99139 -18.04158 -17.04158 -72.99139
    2 -72.99139 -18.04158 -17.04158 -71.99139
    3 -71.99139 -18.04158 -17.04158 -70.99139
    4 -70.99139 -18.04158 -17.04158 -69.99139
    5 -69.99139 -18.04158 -17.04158 -68.99139
    6 -68.99139 -18.04158 -17.04158 -67.99139
    
    #calculate point center
    xcoords <- (df[,"xmax"] - df[,"xmin"])/2 + df[,"xmin"]
    ycoords <- (df[,"ymax"] - df[,"ymin"])/2 + df[,"ymin"]
    
    #create dataframe from coordinates
    points <-data.frame("x"=c(xcoords),
                        "y"=c(ycoords))
    #create raster
    ras <- raster(SpatialPoints(points))