Change longitude from 20 to 380 to -180 to 180 in r raster file

62 Views Asked by At

I'm trying to work with a raster file which has longitude extending from 20 to 380 degrees.

library(raster)
library(ncdf4)
    
raspH <- raster('~/Downloads/GLODAPv2.2016b_MappedClimatologies/GLODAPv2.2016b.pHts25p0.nc', varname = 'pHts25p0', band = 1)

raspH

class      : RasterLayer 
band       : 1  (of  33  bands)
dimensions : 180, 360, 64800  (nrow, ncol, ncell)
resolution : 1, 1  (x, y)
extent     : 20, 380, -90, 90  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : GLODAPv2.2016b.pHts25p0.nc 
names      : seawater.ph.reported.on.total.scale.at.standard.temperature..25C..and.pressure..0dbar. 
z-value    : 1 
zvar       : pHts25p0

plot(raspH) 

enter image description here

The file (netcdf) is from the GLODAP project and can be downloaded here. I'd like to convert this to -180 to 180. Any advice? I imagine the easiest would be to change the longitude first to 0 to 260 degrees by subtracting 360 from all values >360 and then rotate, but how do I go ahead with changing the longitude values in the raster file?

I've also considered changing the longitude directly in the netcdf file, but that messes up the spacing, causing an error when I try to read the file into a raster object.

Any suggestions would be appreciated.

1

There are 1 best solutions below

0
Lukas On

I figured this out based on the rotate function in the raster package

rotateAndShift <- function(x){
  require(raster)
  xr <- xres(x)
  ext1 <- extent(-xr, 180, -100, 100)
  r1 <- crop(x, ext1)

  ext2 <- extent(360+xr, e@xmax, -100, 100)
  r2 <- crop(x, ext2)
  r2 <- shift(r2, -360)

  ext3 <- extent(180, 360+xr, -100, 100)
  r3 <- crop(x, ext3)
  r3 <- shift(r3, -360)
  
  out <- merge(r1, r2, r3, overlap = FALSE)
  
  names(out) <- names(x)
  out@z <- x@z
  
  return(out)
}

it omits several checks that are done in the rotate function, but seems to do the job