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

女生的网名这么多〃 提交于 2019-11-28 07:38:58

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!