I have the following matrix obtained from a NetCDF file that I am trying to convert to a raster. I know that the matrix has a WGS84 projection.
I found one issue that is fixed in the code below - the spacing between the latitudes lat
in NetCDF and consequently in derived matrix clim_ncdf
was not equal. Still, however, the raster EI_adj
is not exactly projected as it should be after conversion from matrix and all spaces are shifted southward.
This problem drives me crazy - does anyone have an idea how to fix it?
Source files (NetCDF and world admin boundaries) can be downloaded from here.
library(raster)
library(ncdf4)
library(lattice)
# Choose variable name
dname <- c("GI")
clim_ncdf <- nc_open("NetCDF_GI.nc")
lon <- ncvar_get(clim_ncdf,"Longitude")
head(lon)
lat <- ncvar_get(clim_ncdf,"Latitude")
# Latitudes have spacing of 0.5 except in two instances:
lat[55:60]
lat[58:59] # problematic ones
# Create a new latitude vector with equal spacing for corrected matrix
nlat <- seq(min(lat),max(lat),0.5)
EI1 <- ncvar_get(clim_ncdf,dname[1])
# This needs to be rotated
rotate <- function(x) t(apply(x, 2, rev))
EI <- rotate(rotate(rotate(EI1)))
# Now adjust EI for the problematic lats:
rows_m_reps <- rep(1,nrow(EI))
rows_m_reps[58] <- 2
rows_m_reps[59] <- 10
# Replicating corresponding rows so we can now have equal latitude distancing
EI_adj <- EI[rep(1:nrow(EI), rows_m_reps), ]
EIr_adj <- raster(EI_adj,xmn=min(lon), xmx=max(lon),ymn=min(nlat),ymx=max(nlat),
crs = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(EIr_adj)
# Add admin layer
library(rgdal)
world_admin <- readOGR("Countries_WGS84.shp")
plot(world_admin, add = TRUE)
Your data
library(ncdf4)
library(raster)
library(maptools)
data(wrld_simpl)
clim_ncdf <- nc_open("NetCDF_GI.nc")
lon <- ncvar_get(clim_ncdf,"Longitude")
lat <- ncvar_get(clim_ncdf,"Latitude")
v <- ncvar_get(clim_ncdf, "GI")
These are all the latitudes.
lat2 <- seq(min(lat),max(lat),0.5)
Create a RasterLayer and a corresponding matrix with NA
s
e <- extent(min(lon)-0.25, max(lon)+0.25, min(lat)-0.25, max(lat)+0.25)
r <- raster(nrow=length(lat2), ncol=length(lon), ext=e)
m <- matrix(NA, nrow=length(lat2), ncol=length(lon))
Now rotate and assign the values to the correct rows for matrix m
vv <- t(v[,ncol(v):1])
i <- rowFromY(r, rev(as.vector(lat)))
m[i,] <- vv
And assign m to the RasterLayer
values(r) <- m
image(r)
lines(wrld_simpl)