简体   繁体   中英

How to create a raster from a data frame in r?

I have a data frame in which values (l) are specified for Cartesian coordinates (x, y) as in the following minimal working example.

set.seed(2013)
df <- data.frame( x = rep( 0:1, each=2 ),
                  y = rep( 0:1,  2),
                  l = rnorm( 4 ))

df
#   x y           l
# 1 0 0 -0.09202453
# 2 0 1  0.78901912
# 3 1 0 -0.66744232
# 4 1 1  1.36061149

I want to create a raster using the raster package, but my reading of the documentation has not revealed a simple method for loading data in the form that I have it into the raster cells. I've come up with a couple ways to do it using for loops, but I suspect that there's a much more direct approach that I'm missing.

An easier solution exists as

 library(raster)
 dfr <- rasterFromXYZ(df)  #Convert first two columns as lon-lat and third as value                
 plot(dfr)
 dfr                  
 class       : RasterLayer 
 dimensions  : 2, 2, 4  (nrow, ncol, ncell)
 resolution  : 1, 1  (x, y)
 extent      : -0.5, 1.5, -0.5, 1.5  (xmin, xmax, ymin, ymax)
 coord. ref. : NA 
 data source : in memory
 names       : l 
 values      : -2.311813, 0.921186  (min, max)

情节

Further, you may specify the CRS string. Detailed discussion is available here.

Here is one approach, via SpatialPixelsDataFrame

library(raster)
# create spatial points data frame
spg <- df
coordinates(spg) <- ~ x + y
# coerce to SpatialPixelsDataFrame
gridded(spg) <- TRUE
# coerce to raster
rasterDF <- raster(spg)
rasterDF
# class       : RasterLayer 
# dimensions  : 2, 2, 4  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent      : -0.5, 1.5, -0.5, 1.5  (xmin, xmax, ymin, ymax)
# coord. ref. : NA 
# data source : in memory
# names       : l 
# values      : -0.6674423, 1.360611  (min, max)

help('raster') describes a number of methods to create a raster from objects of different classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM