# OPeNDAP_subsetting_with_R_tutorial: Author: Maarten Plieger (KNMI), date: 2011-Oct-10 # $Date$ # $Revision$ # $HeadURL$ # This document is also posted on a wiki: http://public.deltares.nl/display/OET/OPeNDAP+subsetting+with+R # R script to obtain data from opendap and convert it to a SpatialGridDataFrame # Install the required packages: # To install sp, use the command: install.packages("sp") # To install ncdf for linux, use the command: install.packages("ncdf") # To install ncdf for Windows, you need to install a precompiled version by: # Menu->Packages->Install Package(s) from local zip files and select ncdf.zip # Pre compiled versions for windows with opendap are currently experimental # Load the packages: library("sp") library("ncdf") getOpenDapURLAsSpatialGrid = function(opendapURL,variableName,bboxInDegrees){ print(paste("Loading opendapURL",opendapURL)); # Open the dataset dataset = open.ncdf(opendapURL) bbox=bboxInDegrees; # Get lon and lat variables, which are the dimensions of depth. For this specific dataset they have the names lon and lat G.x=get.var.ncdf(dataset,"lon") G.y=get.var.ncdf(dataset,"lat") # Make a selection of indices which fall in our subsetting window # E.g. translate degrees to indices of arrays. xindicesinwindow=which(G.x>bbox[1]&G.xbbox[2]&G.y") myspatialgrid; } # Set the bounding box window we want to subset for, in degrees # order: min-x, min-y, max-x, max-y bboxInDegrees=c(0,50,10,55) url_grid = array(); url_grid[1] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/etopo1_bed_g2'; url_grid[2] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/etopo2_v2c.nc'; url_grid[3] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/srtm30plus_v1.nc'; url_grid[4] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/srtm30plus_v6'; url_grid[5] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/smith_sandwell_v9.1.nc'; url_grid[6] = 'http://geoport.whoi.edu/thredds/dodsC/bathy/smith_sandwell_v11'; # Get the data, choose i=1 till 6 i=6; topogrid=getOpenDapURLAsSpatialGrid(url_grid[i] ,"topo",bboxInDegrees); print(paste("mean:",mean(topogrid$topo))); spplot(topogrid,at=c(-60:40,200),col.regions=bpy.colors,main=url_grid[i],xlab=paste("Mean: ",mean(topogrid$topo)))