I have the following NetCDF file - I am trying to convert into raster but something is not right. The projection of the NetCDF file is not given but based on the software I received it from it should LatLong but might be cylindrical equal area. I tried both, but I keep getting this distortion which makes it impossible to query for the values at the right locations. I know the spacing of the grid is not even, not sure if that affects the end result (here visual from ArcGIS but in R it is the same problem unless plotted with levelplot function).
library(raster)
library(ncdf4)
library(lattice)
library(RColorBrewer)
setwd("D:/Results")
climexncdf <- nc_open("ResultsSO_month.nc")
lon <- ncvar_get(climexncdf,"Longitude")
nlon <- dim(lon)
head(lon)
lat <- ncvar_get(climexncdf,"Latitude")
nlat <- dim(lat)
head(lat)
dname <- "Weekly Growth Index"
t <- ncvar_get(climexncdf,"Step")
tmp_array <- ncvar_get(climexncdf,dname)
tmp_stack <- vector("list",length(t))
for (i in 1:length(t)) {
tmp_stack[[i]] <- tmp_array[,,i]
}
YearData <- vector("list",52)
for (i in 1:4) {
YearData[[i]] <- tmp_array[,,i]
}
Month1 <- YearData[c(1,2,3,4)]
# Calculate monthly averages
M1Avg <- Reduce("+",Month1)/length(Month1)
# Replace 0's with NA's
M1Avg[M1Avg==0] <- NA
# Piece of code that gives me what I need:
grid <- expand.grid(lon=lon, lat=lat)
cutpts <- seq(0,1,0.1)
# Convert to raster - work to include lat and long
M1Avg_reorder <- M1Avg[ ,order(lat) ]
M1Avg_reorder <- apply(t(M1Avg_reorder),2,rev)
M1AvgRaster <- raster(M1Avg_reorder,
xmn=min(lon),xmx=max(lon),
ymn=min(lat),ymx=max(lat),
crs=CRS("+proj=longlat +datum=WGS84"))
#crs=CRS("+proj=cea +lat_0=0 +lon_0=0"))
r <- projectRaster(M1AvgRaster,crs=CRS("+proj=longlat +datum=WSG84"))
plot(M1AvgRaster)
# Location file not included but any locations can be entered
locations <- read.csv("Locations.csv", header=T)
coordinates(locations) <- c("y","x")
data <- extract(M1AvgRaster,locations)
writeRaster(M1AvgRaster, "M1AvgRaster_Globe_projWGSTest", format = "GTiff")