How can I convert data in the form of lat, lon, value into a raster file using R?
Several steps required:
You say it's a regular 1km grid, but that means the lat-long aren't regular. First you need to transform it to a regular grid coordinate system so the X and Y values are regularly spaced.
a. Read it into R as a data frame, with columns x, y, yield.
pts = read.table("file.csv",......)
b. Convert the data frame to a SpatialPointsDataFrame using the sp package and something like:
library(sp) library(rgdal) coordinates(pts)=~x+y
c. Convert to your regular km system by first telling it what CRS it is, and then spTransform to the destination.
proj4string(pts)=CRS("+init=epsg:4326") # set it to lat-long pts = spTransform(pts,CRS("insert your proj4 string here"))
d. Tell R that this is gridded:
gridded(pts) = TRUE
At this point you'll get an error if your coordinates don't lie on a nice regular grid.
Now use the raster package to convert to a raster and set its CRS:
r = raster(pts) projection(r) = CRS("insert your proj4 string here")
Now have a look:
plot(r)
Now write it as a geoTIFF file using the raster package:
writeRaster(r,"pts.tif")
This geoTIFF should be readable in all major GIS packages. The obvious missing piece here is the proj4 string to convert to: this will probably be some kind of UTM reference system. Hard to tell without some more data...
Since the question was last answered, a much easier solution exists by using the raster package's rasterFromXYZ
function that encapsulates all of the steps necessary (including specification of the CRS string).
library(raster)
rasterFromXYZ(mydata)