[R] Lat Lon NetCDF subset

David Pierce dpierce at ucsd.edu
Mon Mar 21 19:35:29 CET 2011


hgreatrex wrote:
> Hi,
>
> ...
> I've managed to extract the lat / lon variables, so I know that I could
> work
> out manually which pixels correspond to which location. However, it's easy
> to make a mistake in such a calculation, so I thought I would check here
> before reinventing the wheel.

Hi hgreatrex,

this is an example of how I approach this problem, which works for me but
may or may not work for you. :)

CCD20 = open.ncdf("ccd1983_01-dk1_20.nc")
lat = CCD20$dim$lat$vals   # NOTE: dim values are CACHED, don't read them
lon = CCD20$dim$lon$vals

lower_left_lon_lat = c(5,30)
upper_right_lon_lat = c(10,40)

ix0 = wherenearest( lower_left_lon_lat[1],  lon )
ix1 = wherenearest( upper_right_lon_lat[1], lon )
iy0 = wherenearest( lower_left_lon_lat[2],  lat )
iy1 = wherenearest( upper_right_lon_lat[2], lat )

countx = ix1 - ix0 + 1
county = iy1 - iy0 + 1

z = get.var.ncdf( CCD20, "data", start=c(ix0,iy0), count=c(countx,county)

Obviously, you can easily wrap into a separate function an extended
version of 'get.var.ncdf' that takes lat/lon values rather than indices. 
The 'wherenearest(val,matrix)' function is probably obvious, but is
something like this:

dist = abs(matrix-val)
index = which.min(dist)
return( index )

Hope that helps,

--Dave

-------------------------------------------------------------------
David W. Pierce
Division of Climate, Atmospheric Science, and Physical Oceanography
Scripps Institution of Oceanography
(858) 534-8276 (voice)  /  (858) 534-8561 (fax)    dpierce at ucsd.edu



More information about the R-help mailing list