[GIS] Create Raster file in R from Matrix and latlons

rraster

I could use some advice on how to create a Raster file in R with a Matrix of data points and the coordinates stored in a separate file.
Both, data and coordinates come from a NetCDF file. I extracted the data and made some calculations that resulted in a matrix looking similar to this one:

NA NA NA 12 NA NA NA
NA 23 34 13 45 NA NA
23 12 12 23 34 54 56
NA NA NA NA 23 21 NA

With the difference, that there are 79 rows and 78 columns.
The unprojected coordinates represent the centroids of the raster and can be extracted from the NetCDF file. Logically the longitude coordinates have a length of 79 and the latitude of 78. i saw a very good answer on a similar problem here on GIS Stack Exchange but I'm not quite sure if I can apply the solution to my problem since my data structure is different and my coordinates are not projected. Maybe one solution would be to project the coordinates and then make a long table reshaping the data with the coordinates. But maybe there is also an easier solution…

csv files containing the data and the original netCDF can be found here. Any help would be very appreciated!!!

Best Answer

You can do

matrix <- matrix(1:16, nrow=4)
library(raster)
r <- raster(matrix)
# replace with correct coordinates
extent(r) <- c(0, 1, 0, 1)
r <- writeRaster(r, 'filename.tif')

But your question suggests that you would have been better of accessing the ncdf file as a RasterLayer object (and avoid creating matrices and keeping track of coordinates)

 pft <- raster("pft_harvest_maize.nc")

etc.

Related Question