Introduction to R+OSGeo (software installation and first steps) Tomislav Hengl ISRIC World Soil Information, Wageningen University
About myself Senior researcher at ISRIC World Soil Information; PhD in pedometric mapping @ ITC (GIS institute in Enschede) in 2003; 2 years university assistant; 2.5 years JRC Ispra; 2 years University of Amsterdam; My expertise: Geostatistics, Digital Soil Mapping, spatial data analysis, geomorphometry (vice-chair); Global Soil Information Facilities
My publications
GEOSTAT What is GEOSTAT?
GEOSTAT GEOSTAT is a non-profit, specialized, block course (summer school) run by FOSS enthusiasts and developers. The main idea of GEOSTAT is to promote various aspects of statistical analysis of spatial and spatio-temporal data using open source / free GIS tools: R, SAGA GIS, GRASS GIS, FWTools, Google Earth and similar.
The happy triangle Statistical computing GDAL GRASS GIS GIS analysis ground overlays, time-series Browsing of geo-data KML
Previous meetings 2007 Naples (IT) 2008 Amsterdam (NL) 2009 Split (HR) 2010 Plasencia (ES) 2011 Landau (GE) Local GEOSTAT: Zagreb (2004), Ispra (2007), Canberra (2011), Belgrade (2011)
What is a crash course A crash course is a compressed version of a training course for people that already have full agendas. It is really intended for people who pick up new methods/tools quickly and have a high motivation to learn (PhD students?). This means no long questions, no going back, no deep discussion, no complains about the speed/programme of the course... and of course: no promises that you will manage to master these tools in such a short time.
PhD Comics
Main principles 1. The location is selected by the lecturers. 2. The course programme is largely shaped by the participants. 3. Selection of candidates is based on solidarity, academic output and contributions to open source projects. 4. Participants come with their own laptop computers. 5. GEOSTAT makes no profit.
100% pure enthusiasm
Belgrade 2008/2009
The six pillars of open geo-data production 1 1. open data, in real-time 2. open source geospatial software 3. open, reproducable procedures 4. open, web-based, methods for data and processing models (interoperability) 5. open and explicitly quantified significance and accuracy levels of research findings 6. managed, open user and developer communities 1 Edzer Pebesma, (OpenGeostatistic.org)
General structure DAY 1: Introduction and course overview (software installation and first (baby) steps in R). DAY 2: Open Source GIS day. DAY 3: Spatio-temporal data in R (linking R with GIS, MySQL). DAY 4: Sensor Web and SWE hands on with INTAMAP, WPS, and RServe. DAY 5: Open day (the programme will be published on Day 4)
Types of internal courses You loose time, we loose time.
Types of internal courses You loose time, we loose time. You loose time (we practice teaching).
Types of internal courses You loose time, we loose time. You loose time (we practice teaching). We loose time.
Types of internal courses You loose time, we loose time. You loose time (we practice teaching). We loose time. You run a similar course in 1 2 years.
Literature I Beaudette, D., 2009. Open Source Software Tools for Soil Scientists. University of California at Davis. Bivand, R., Pebesma, E., Rubio, V., 2008. Applied Spatial Data Analysis with R. Use R Series, Springer, Heidelberg, pp. 378. Conrad, O. 2007: SAGA Entwurf, Funktionsumfang und Anwendung eines Systems für Automatisierte Geowissenschaftliche Analysen. electronic doctoral dissertation, University of Göttingen. Hengl, T. 2009. A Practical Guide for Geostatistical Mapping. University of Amsterdam, (lulu.com). Kabacoff, R.I., 2009. Data Analysis and Graphics with R. Manning publications, 375 p.
Literature II Neteler, M., Mitasova, H., 2008. Open Source GIS: A GRASS GIS Approach, 3rd Edt. Springer, The International Series in Engineering and Computer Science: Volume 773. 406 p. Venables, W.N. et al, 2010. Introduction to R. R Core Development team.
Some important assumptions Some of you are experienced users (20 30% are beginners).
Some important assumptions Some of you are experienced users (20 30% are beginners). Most of you are new to SAGA / GRASS (you need a gentle intro).
Some important assumptions Some of you are experienced users (20 30% are beginners). Most of you are new to SAGA / GRASS (you need a gentle intro). R is hot.
Some important assumptions Some of you are experienced users (20 30% are beginners). Most of you are new to SAGA / GRASS (you need a gentle intro). R is hot. It has a steep learning curve: R is hell.
Some important assumptions Some of you are experienced users (20 30% are beginners). Most of you are new to SAGA / GRASS (you need a gentle intro). R is hot. It has a steep learning curve: R is hell. You all have various backgrounds and see world with different eyes.
Disclaimer We can give you an overview of R+OSGeo in 5 days; we can NOT teach you statistics, GIS, RS, computer science... in 40 hours.
Disclaimer We can give you an overview of R+OSGeo in 5 days; we can NOT teach you statistics, GIS, RS, computer science... in 40 hours. Lecturers are not responsible for Internet, coffee breaks, lunches, local logistics etc.
Disclaimer We can give you an overview of R+OSGeo in 5 days; we can NOT teach you statistics, GIS, RS, computer science... in 40 hours. Lecturers are not responsible for Internet, coffee breaks, lunches, local logistics etc. Local organizers (Branislav) is not responsible for the program (or a complete lack of it).
Getting the right motivation (inspiration) Why should you invest time to learn to speak R? What can it do? (and what it can t do?) How does the R-sig-geo community works (what are its shared principles)? How does the OSgeo community works (what are its shared principles)? Is R+SAGA/GRASS the best choice for spatio-temporal data analysis?
The open source movement Open Source solutions 2 : Operating systems: Linux Databases: SQL Scientific writing: L A TEX Spatial analysis: GRASS GIS, SAGA GIS Statistical computing: R 2 http://www.gnu.org/philosophy/fsfs/rms-essays.pdf
Quote To build a better world we need to replace the patchwork of lucky breaks and arbitrary advantages that today determine success the fortunate birth dates and the happy accidents of history with a society that provides opportunities for all. Malcom Gladwell in Outliers.
FOSS and academic work
R Why R?
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team);
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team); why R?: the name R was selected for two reasons: (1) precedence R is a letter before S, and (2) coincidence both of the creators names start with a letter R ;
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team); why R?: the name R was selected for two reasons: (1) precedence R is a letter before S, and (2) coincidence both of the creators names start with a letter R ; it is a computer language developed to simplify statistical computing/programming;
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team); why R?: the name R was selected for two reasons: (1) precedence R is a letter before S, and (2) coincidence both of the creators names start with a letter R ; it is a computer language developed to simplify statistical computing/programming; it offers many contributed packages (>2000), technical documents, demos and examples;
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team); why R?: the name R was selected for two reasons: (1) precedence R is a letter before S, and (2) coincidence both of the creators names start with a letter R ; it is a computer language developed to simplify statistical computing/programming; it offers many contributed packages (>2000), technical documents, demos and examples; widely recognized as one of the fastest growing and most comprehensive statistical computing tools;
What is R? the open source implementation of the S language for statistical computing created by created by Ross Ihaka and Robert Gentleman (now maintained by the R Development Core Team); why R?: the name R was selected for two reasons: (1) precedence R is a letter before S, and (2) coincidence both of the creators names start with a letter R ; it is a computer language developed to simplify statistical computing/programming; it offers many contributed packages (>2000), technical documents, demos and examples; widely recognized as one of the fastest growing and most comprehensive statistical computing tools; it is a movement;
R is sexy
What it is not it s not a software with GUI and point-and-click control;
What it is not it s not a software with GUI and point-and-click control; there are practically no data analysis wizards;
What it is not it s not a software with GUI and point-and-click control; there are practically no data analysis wizards; it s not an interactive system!;
What it is not it s not a software with GUI and point-and-click control; there are practically no data analysis wizards; it s not an interactive system!; it comes with no warranties (but so does the commercial software too!!);
What it is not it s not a software with GUI and point-and-click control; there are practically no data analysis wizards; it s not an interactive system!; it comes with no warranties (but so does the commercial software too!!); there is practically no formal support;
Why make scripts? Roger Bivand: Because S (and its implementation R) is a well-developed, simple and effective programming language which includes conditionals, loops, user-defined recursive functions and input and output facilities, existing functions can be modified. This is what is referred to as statistical programming in R we all become programmers (but much faster than with C++ or Java).
Why make scripts? Roger Bivand: Because S (and its implementation R) is a well-developed, simple and effective programming language which includes conditionals, loops, user-defined recursive functions and input and output facilities, existing functions can be modified. This is what is referred to as statistical programming in R we all become programmers (but much faster than with C++ or Java). The basic approach to using R is to generate scripts that define the data processing steps (workflows?).
Why make scripts? Roger Bivand: Because S (and its implementation R) is a well-developed, simple and effective programming language which includes conditionals, loops, user-defined recursive functions and input and output facilities, existing functions can be modified. This is what is referred to as statistical programming in R we all become programmers (but much faster than with C++ or Java). The basic approach to using R is to generate scripts that define the data processing steps (workflows?). Documenting the analysis process is a good thing, so programming scripts are not just a burden, certainly for users doing original research and repetetive work, arguably for student classes too.
Why make scripts? Roger Bivand: Because S (and its implementation R) is a well-developed, simple and effective programming language which includes conditionals, loops, user-defined recursive functions and input and output facilities, existing functions can be modified. This is what is referred to as statistical programming in R we all become programmers (but much faster than with C++ or Java). The basic approach to using R is to generate scripts that define the data processing steps (workflows?). Documenting the analysis process is a good thing, so programming scripts are not just a burden, certainly for users doing original research and repetetive work, arguably for student classes too. Point-and-click operations are for little children!
Do you speak R? After some time you basically discovered that most of the things you want to do, you can do in R, the only question is how. Well, first, you have to learn to how to speak n write R.
A bit of history R was first time released in 1997; majority of the development is (still) done by prof.brian D. Ripley; at the moment (september 19 2011 18:50), there are 3228 contributed packages! according to Google trends, R-project.org has a community of about 200 350k active users; in 2003, a group of researchers (International Workshop on Distributed Statistical Computing) decided to add spatial functionality to R;... now is time to use it more broadly (MSc level and PhD level modules, projects, reports and scientific documents);
Quote Once methodological problems start being perceived or even defined in terms of what one s favorite software does well, then the software has stopped being a tool, and has become a crutch, and at worse a shackle. Simon Jackman
Quote R has really become the second language for people coming out of grad school now, and there s an amazing amount of code being written for it. Max Kuhn
Why I use R? It s provides analysis tools of highest quality (top scientistis work with R).
Why I use R? It s provides analysis tools of highest quality (top scientistis work with R). It s reliabile (it s open).
Why I use R? It s provides analysis tools of highest quality (top scientistis work with R). It s reliabile (it s open). It s developing at faster speed.
Why I use R? It s provides analysis tools of highest quality (top scientistis work with R). It s reliabile (it s open). It s developing at faster speed. It expands my creativity.
Why I use R? It s provides analysis tools of highest quality (top scientistis work with R). It s reliabile (it s open). It s developing at faster speed. It expands my creativity. It s free.
The ASDA(R)-book.org
The ASDA(R) team
A Practical Guide to Geostatistical Mapping
Quote I created Quick-R for one simple reason. I wanted to learn R and I am a teacher at heart. The easiest way for me to learn something is to teach it Robert I.Kabacoff
Software Not all software is required to follow the exercises R v2.13 (Windows OS) including a list of packages; Tinn-R v2.3 (code editor); ODBC driver for windows; Optional: FWTools v2.4 a list of utilities to handle spatial data; SAGA GIS v2.0.7 a light GIS excellent for educational purposes.
Installing the add-on packages > install.packages("ctv") > library(ctv) > install.views("spatial") This will install all connected packages listed at views/spatial.
Check your installation > Sys.getenv(c("OS", "COMPUTERNAME", "R_HOME", "R_LIBS_USER", + "PROCESSOR_IDENTIFIER")) OS "Windows_NT" COMPUTERNAME "L0130840" R_HOME "C:\\PROGRA~1\\R\\R-212~1.2" R_LIBS_USER "M:\\My Documents/R/win-library/2.12" PROCESSOR_IDENTIFIER "Intel64 Family 6 Model 30 Stepping 5, GenuineIntel"
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.).
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.:
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically;
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ;
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ; Quick-R;
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ; Quick-R; 3. If your R script does not work, do not break your head, try to get help:
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ; Quick-R; 3. If your R script does not work, do not break your head, try to get help: local installation (> help.search("kriging"));
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ; Quick-R; 3. If your R script does not work, do not break your head, try to get help: local installation (> help.search("kriging")); R-project (> RSiteSearch("krige dimensions do not match"))
Making friends with R 1. Use script editors such as as TINN-R or JGR (syntax highlighting, wrapping, search/replace etc.). 2. The best way to learn R is to look at the existing scripts, then adjust/improve/extend/combine them to fit your needs, e.g.: Graphical Manual/Addicted to R if you prefer to explore examples graphically; Teach-your-self books e.g. Statistics with R or An Introduction to R ; Quick-R; 3. If your R script does not work, do not break your head, try to get help: local installation (> help.search("kriging")); R-project (> RSiteSearch("krige dimensions do not match")) www Rseek.org
Good practice Put comments in script (after #). Add some meta-information at the beginning of your script. Once you tested your script and saw that it works, tidy-up the code. Place the input data on-line (database) so you can communicate only the script.
R mailing lists: Do s and Don ts! Do s: If you have not done so already, read the R posting guide. Use the existing pre-installed datasets (come together with a certain package) to describe your problem; link your problem to some existing problems. Acknowledge the work (time spent) other people do to help you. You can submit not only the problems you discover but also the information that you think is interesting for the community. Don ts: Do not send poorly formulated questions. Do not send too much. Complaining to a mailing list about what frustrates you about R makes no sense. You are requesting that somebody does a work for you that you could do yourself!
R GUI
JaGuaR
RStudio
New function > name <- function(arg_1, arg_2,...) expression
Example > sum2 <- function(x, y) { + sum2 <- x + y + return(sum2) + } > sum2(5, 6) [1] 11
Spatial objects An advantage of R is that you can create your own formats and structures for data. But if there are too many formats you can easily get lots. In addition, we want to have smooth links to external formats (R is open!). To reduce this problem, Bivand et al.(2008) developed new-style classes to represent spatial data.
Spatial class The foundation object is the Spatial class, with just two slots (new-style class objects have pre-defined components called slots): a bounding box mostly used for setting up plots; a CRS class object defining the coordinate reference system, and may be set to CRS(as.character(NA)); Operations on Spatial* objects should update or copy these values to the new Spatial* objects being created. The most basic spatial data object is a point, which may have 2 or 3 dimensions.
Spatial classes for point features: SpatialPoints; SpatialPointsDataFrame; for line features: SpatialLines, SpatialLinesDataFrame; polygons: SpatialPolygons, SpatialPolygonsDataFrame; rasters: SpatialPixels, SpatialPixelsDataFrame, SpatialGrid, SpatialGridDataFrame;
SpatialPoints > library(sp) > data(meuse) > coords <- SpatialPoints(meuse[, c("x", "y")]) > summary(coords) Object of class SpatialPoints Coordinates: min max x 178605 181390 y 329714 333611 Is projected: NA proj4string : [NA] Number of points: 155
SpatialPointsDataFrame We can add the tabular data to make a SpatialPointsDataFrame object: > meuse1 <- SpatialPointsDataFrame(coords, meuse) > str(meuse1, max.level = 2) Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots..@ data :'data.frame': 155 obs. of 14 variables:..@ coords.nrs : num(0)..@ coords : num [1:155, 1:2] 181072 181025 181165 181298 181307.......- attr(*, "dimnames")=list of 2..@ bbox : num [1:2, 1:2] 178605 329714 181390 333611....- attr(*, "dimnames")=list of 2..@ proj4string:formal class 'CRS' [package "sp"] with 1 slots
Point features Spatial points classes and their slots SpatialPointsDataFrame SpatialPoints coords.nrs data data.frame Spatial bbox proj4string SpatialPoints coords Spatial Spatial lines and polygons
Spatial Line/polygon Polygonsfeatures classes and slots SpatialLines lines Spatial Lines Lines ID Line coords SpatialPolygons polygons plotorder Spatial Spatial bbox proj4string Polygons Polygons plotorder labpt ID area Polygon labpt area hole ringdir coords
Grids Spatial grid and pixels classes and their slots SpatialGridDataFrame SpatialGrid data SpatialPixelsDataFrame SpatialPixels data data.frame SpatialGrid grid grid.index SpatialPoints SpatialPixels grid grid.index SpatialPoints GridTopology cellcentre.offset cellsize cells.dim Spatial bbox proj4string SpatialPoints coords Spatial Spatial classes provided by sp
Basic methods spplot plotting of spatial objects (maps); spsample sample points from a set of polygons, on a set of lines or from a gridded area; bbox get the bounding box; proj4string get or set the projection (coordinate reference system); coordinates set or retrieve coordinates; sptransform transform coordinates from one CRS to another; overlay combine two different spatial objects;
Plotting a SpatialPoints object > plot(as(meuse1, "Spatial"), axes = TRUE) > plot(meuse1, add = TRUE) > plot(meuse1[meuse1$ffreq == 1, ], col = "green", add = TRUE) 330000 331000 332000 333000 178000 179000 180000 181000 182000
Combining statistical and GIS operations Because the Spatial*DataFrame family objects behave in most cases like data frames, most of what we are used to doing with standard data frames just works (but no merge, etc., yet). These objects are very similar to typical representations of the same kinds of objects in geographical information systems, so they do not suit spatial data that is not geographical (like medical imaging) as such. Because now sp classes for GIS data exits, this opens the door for fusing GIS and statistical operations (this has not been possible in e.g.2002).
Spatial packages R now offers a range of contributed packages in spatial statistics and increasing awareness of the importance of spatial data analysis in the broader community. Current contributed packages with spatial applications: point patterns: spatstat, VR:spatial, splancs; geostatistics: gstat, geor, georglm, fields, spbayes, RandomFields, VR:spatial, sgeostat, vardiag; lattice/area data: spdep, DCluster, spgwr, ade4; links to GIS: rgdal, spgrass, RPy, RSAGA;
Let s create spatial objects! We can create spatial objects from scratch! For example a DEM: > dem <- expand.grid(x = seq(100, 600, 100), y = seq(100, + 600, 100)) > dem$z <- as.vector(c(23, 24, 34, 38, 45, 51, 24, 20, + 20, 28, 18, 49, 22, 20, 19, 14, 38, 45, 19, 15, 13, + 21, 23, 25, 14, 11, 18, 11, 18, 19, 10, 16, 23, 16, + 9, 6)) > gridded(dem) <- ~x + y > dem <- as(dem, "SpatialGridDataFrame") > str(dem)
A small DEM > dem.plt <- spplot(dem[1], main = "DEM", scales = list(draw = FALSE), + col.regions = topo.colors(25)) > print(dem.plt) > writegdal(dem, "dem6.sdat", "SAGA") DEM 50 40 30 20 10
Controlling SAGA from R > library(rsaga) > rsaga.env() $workspace [1] "." $cmd [1] "saga_cmd.exe" $path [1] "C:/PROGRA~1/R/R-212~1.2/library/RSAGA/saga_vc" $modules [1] "C:/PROGRA~1/R/R-212~1.2/library/RSAGA/saga_vc/modules" $version [1] "2.0.7"
Getting list of modules > rsaga.get.modules("ta_channels") $ta_channels code name interactive 1 0 Channel Network FALSE 2 1 Watershed Basins FALSE 3 2 Watershed Basins (Extended) FALSE 4 3 Vertical Distance to Channel Network FALSE 5 4 Overland Flow Distance to Channel Network FALSE 6 5 D8 Flow Analysis FALSE 7 6 Strahler Order FALSE
Run stream extraction > rsaga.geoprocessor(lib = "ta_channels", module = 5, param = list(dem = "dem6.sg + DIRECTION = "channels.sgrd", CONNECTION = "route.sgrd", + NETWORK = "channels.shp")) library path: C:/PROGRA~1/R/R-212~1.2/library/RSAGA/saga_vc/modules library name: ta_channels module name : D8 Flow Analysis author : (c) 2003 by O.Conrad Load grid: dem6.sgrd... ready Load grid: channels.sgrd... ready Load grid: route.sgrd... ready Load shapes: channels.shp... ready
Read back to R > dem$route <- readgdal("route.sdat")$band1 route.sdat has GDAL driver SAGA and has 6 rows and 6 columns > channels <- readogr("channels.shp", "channels") OGR data source with driver: ESRI Shapefile Source: "channels.shp", layer: "channels" with 32 features and 2 fields Feature type: wkblinestring with 2 dimensions
Plot the final result > dem.plt <- spplot(dem[1], main = "DEM", col.regions = topo.colors(25)) > channels.plt <- spplot(dem[2], col.regions = rev(gray(0:20/20)), + main = "Flow connectivity", sp.layout = list("sp.lines", + channels, col = "red")) > print(dem.plt, split = c(1, 1, 2, 1), more = T) > print(channels.plt, split = c(2, 1, 2, 1), more = F) DEM Flow connectivity 50 4.0 3.5 40 3.0 2.5 30 2.0 1.5 20 1.0 10 0.5 0.0
FWTools There is still no package to control FWTools from R, but we can simply send command lines. Before we can use FWTools from R, we need to locate it on our PC: > gdalwarp <- gsub("/", "\\\\", dir(path="c:/progra~1/fwtool~1.7", + pattern="gdalwarp.exe", recursive=true, full.names=true)) > gdalwarp [1] "C:\\PROGRA~1\\FWTOOL~1.7\\bin\\gdalwarp.exe" > workd <- paste(gsub("/", "\\\\", getwd()), "\\", sep="")
MODIS data Now we can download some GIS data from web: > MOD12Q1 <- "ftp://anonymous:test@e4ftl01u.ecs.nasa.gov/ + MOLT/MOD12Q1.004/2004.01.01/" > download.file(paste(mod12q1, + "MOD12Q1.A2004001.h18v03.004.2006117173748.hdf", sep=""), + destfile=paste(getwd(), + "MOD12Q1.A2004001.h18v03.004.2006117173748.hdf", sep="/"), + mode='wb') Resolving e4ftl01u.ecs.nasa.gov... 152.61.4.83 Connecting to e4ftl01u.ecs.nasa.gov 152.61.4.83 :21... connected. Logging in as anonymous... Logged in! ==> SYST... done. ==> PWD... done. ==> TYPE I... done. ==> CWD /MOLT/MOD12Q1.004/2004.01.01... done. ==> SIZE MOD12Q1.A2004001.h18v03.004.2006117173748.hdf... 23165983 ==> PASV... done. ==> RETR MOD12Q1.A2004... done. Length: 23165983 (22M) 0K...... 0% 64.9K 5m48s... 22550K...... 99% 501K 0s 22600K... 100% 503K=65s
Reprojecting grids We can reproject/resample the map to our local coordinate system using the gdalwarp functionality (this combines several processing steps in one function): > NL.prj <- "+proj=sterea +lat_0=52.15616055555555 + +lon_0=5.38763888888889 +k=0.999908 +x_0=155000 + +y_0=463000 +ellps=bessel +units=m +no_defs + +towgs84=565.237,50.0087,465.658, + -0.406857,0.350733,-1.87035,4.0812" > system(paste(gdalwarp, " HDF4_EOS:EOS_GRID:\"", workd, + "\\MOD12Q1.A2004001.h18v03.004.2006117173748.hdf\" + :MOD12Q1:Land_Cover_Type_1 -t_srs \"", NL.prj, "\" + IGBP2004NL.tif -r near -te 0 300000 280000 625000 + -tr 500 500", sep="")) Creating output file that is 560P x 650L. Processing input file HDF4_EOS:EOS_GRID:\\MOD12Q1.A2004001... Using internal nodata values (eg. 255) for image HDF4_EOS:EOS_... 0...10...20...30...40...50...60...70...80...90...100 - done.
Plot the final result In this case we have produced a MODIS-based land cover map for the whole Netherlands in resolution of 500 m (in local coordinate system).
ODBC Open Database Connectivity (ODBC) an DB independent software interface (driver library); RODBC allows you to connect to a remote or local database and send SQL queries from R. Basically, by using RODBC we should be able to connect to any database (R/W).
Add DSN
Writing spatial data to KML There are two possibilities to export maps to KML: (a) using existing packages, and (b) by writing KML files by-hand. To export point or line features to KML, use the writeogr method that is available in R package rgdal. More flexible way to writing KML files is by using loops.