Skip to content

Instantly share code, notes, and snippets.

@mbacou
Last active October 4, 2016 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbacou/784d23f3c32c68b569fe83a6cf08924b to your computer and use it in GitHub Desktop.
Save mbacou/784d23f3c32c68b569fe83a6cf08924b to your computer and use it in GitHub Desktop.
Convert SPAM from CSV to netCDF format
# Load some R libraries
library(data.table)
library(raster)
# Load CELL5M grid coordinates
grid <- fread("hc_seq_5m.csv")
# Load SPAM from CSV format
spam.a <- fread("spam2005V3r0_SSA_A.csv")
# Add X,Y coordinates to SPAM variables (they're not in the v3r0 files)
setkey(grid, CELL5M)
setkey(spam.a, cell5m)
spam.a <- grid[spam.a]
# Convert to multi-band raster
vars <- names(spam.a)[13:222] # keep only `whea` to `rest_s` columns
spam.a <- SpatialPixelsDataFrame(
spam.a[, .(X, Y)],
data.frame(spam.a[, .SD, .SDcols=vars]),
proj4string=CRS("+init=epsg:4326"))
spam.a <- brick(spam.a)
names(spam.a) <- vars
# Set -9999 to NA values (if any)
NAvalue(spam.a) <- -9999
# Plot e.g. wheat
spplot(spam.a[["whea"]])
# Save 210-layer raster to e.g. netCDF format
writeRaster(spam.a, "spam2005V3r0_SSA_A.nc",
longname="SPAM 2005 v3r0 Physical Area", varname="A", varunit="ha", zname="crop")
# Else only save a few crops of interest to ESRI Ascii raster
writeRaster(spam.a[[c("whea", "maiz")]], "spam2005V3r0_SSA_A.asc", bylayer=TRUE, options="TFW=YES")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment