African drone and data academy
GIS and Data Analytics Module
Ir. Emmanuel Chinkaka
echinkaka@[Link]
+265997559996
20th August 2020
GIS Programming with R
What you will learn?
This section of the course is designed to :
– Serve as an introduction to R language and its uses
– Teach you the basics of R syntax
– Illustrate some of R‟s graphical capabilities
What is R?
R is a language and environment for
statistical computing and graphics
R environment has the following:
– An effective data handling and storage facility
– A suit of operators for calculations on arrays, matrices
– A large, coherent, integrated collection of intermediate tools for
data analysis
– Graphical facilities for data analysis and display
– a well developed, simple and effective programming
language.
Why use R for Mapping and Spatial
Data Analysis?
Has advanced analysis, modelling and visualization capabilities
Is multi-platform
R is open source
R has a wide range of packages which makes it support
advanced geospatial statistics, modelling and visualization
R is user friendly -RStudio IDE has made it so
Has a bridge to other GIS software
R supports interactive mapping
R is an interpreted language:
– code entered into the console is immediately executed and the result
printed rather than waiting for the immediate stage of compilation
Why use R for Mapping and Spatial
Data Analysis?
Has advanced analysis, modelling and visualization capabilities
Is multi-platform
R is open source
R has a wide range of packages which makes it support
advanced geospatial statistics, modelling and visualization
R is user friendly -RStudio IDE has made it so
Has a bridge to other GIS software
R supports interactive mapping
R is an interpreted language:
– code entered into the console is immediately executed and the result
printed rather than waiting for the immediate stage of compilation
RStudio
RStudio
RStudio is an integrated development environment (IDE) for R
RStudio components:
– A console
– Syntax_highlighting editor
– Work space management
RStudio is available in open source and commercial editions
RStudio runs on the desktop(Windows, Mac and Linux) or in a
browser connected to RStudio Server
Installing RStudio
Download and install the latest free version
of RStudio Desktop based on your platform
– Webpage:[Link]
wnload/#download
RStudio requires R. Download the latest
version of R compatible to your platform:
– Webpage: [Link]
Rstudio
When you just open a new Rstudio project,
the GUI is as shown below:
RStudio
Script: Where Environment/History/
you write your Connections
code
Files/Plots/Packages
Console: Where /Help/Viewer
R code is
executed
RStudio
Click on File>New File>R Script script to
open a new R script
An R script is a an editor where you write
your code
Setting a working directory(wd) in
RStudio
Before you begin working in R, you should set your
working directory
Working directory: folder to hold all your
files(scripts, input data and outputs eg. “C/R GIS
short course”
To change wd in Rstudio:
– Select main menu Session>>Set Working Directory>>..
– From files tab click More>>Set As Working Directory
Uses the current location of the files as your wd
Setting wd in
RStudio
Setting a wd in RStudio
A wd can also be set in the Console with the
setwd() command:
Example: the command below sets the r and
gis course folder located in C drive as a
working directory
– setwd(“C/GIS in R Codes”)
To check the file path of current directory:
– getwd()
RStudio Projects(.Rproj files)
Contains information about the specific
settings you may have set for a project.
Open or create projects using the drop down
menu in the top left-hand corner of RStudio
R Project drop down menu
You can create new projects
from existing or new
directories with “New
Project….”
When you click “Open
Project…”, wd is
automatically set to the Rproj
file‟s location
Any projects you have
created or used recently will
show up in the “Project List”
R scripts
Rstudio‟s source tab serves as a built-in text
editor
Commands are written down before executing
functions at the console
Importance of scripting:
– Allows others to reproduce your work
– Serves as instruction/reminder on how to perform a
task
Basics of R scripting
To write script, open a new R script file by clicking
File>New>File>R Script.
Within the text editor, you can type out a sequence of functions
Place each function on a separate line
If a function has a long list of arguments, place each argument on a
separate line
A command can be executed from the text editor by placing the cursor
on a line and pressing Ctrl+Enter, or clicking the Run button.
An entire script can be executed by clicking the Source button
R scripting
Saving R Files
Several types of files that can be saved:;
– Workspace
– Script
– History
– graphics
R script(.R)
Is a text file of R commands that you have
typed
To save R scripts in Rstudio:
– Click save button from R script tab and save with
the .R extension
– To open R script, click the file icon
R workspace(.Rdata)
Consists of all data objects created or loaded
during the R session
The workspace file ,.Rdata is saved in the
working directory.
You can save or load your workspace at any
time during your R session from the menu:
Session>Save Workspace As…, or the
save button on the Environment Tab
Workspace(.Rdata)
R command for saving workspace
– [Link](file=“[Link]”)
R Graphics
These can be saved in various formats eg,
pdf, png, jpeg etc.
R help
R has an inbuilt help facility
Used to get information on any particular
Examples:
– help(solve) or ?solve: gets more information on the
solvefunction
– [Link](): launches a Web browser that allows the help
pages to be browsed with hyperlinks
– ??: help search command for searching help in various
ways
– ?[Link] : help search command for searching help
in various ways
– example(topic): runs examples on a help topic
R syntax
R is case sensitive: „A‟ and „a‟ are different
symbols and would refer to different
variables
R names can be alphanumeric symbols
plus „ . ‟, „_‟.
R names must start with „ . ‟, or a letter, and if
it starts with „.‟ the second character must not
be a digit.
Length of R names is unlimited.
R syntax
Commands are separated either by a semi-colon(;)
or by a newline
Elementary commands can be grouped together
into one compound expression by braces(„{„ and „}‟)
Comments can be put almost anywhere with a
hashmark („#‟). Everything to the end of the line is
a comment.
Variable assignment in R
A Variable allows you to store a value (e.g.
10)or an object(e.g. a function description) in
R
You can the later use the variable‟s name to
access the value or object stored within the
variable
Variable assignment in R
R assignment operators:
– <-: consists of the „<‟ („less than‟) and „-‟ („minus‟)
characters e.g. x <- 2
– = : The equal to operator e.g. x = 2
Assignment can also be done using
assign() function e.g. assign(„x‟, 2)
Variable assignment in R
Variables are not declared as some data
type in R as it is with other programming
languages(C or Java)
Variables are assigned with R-object and the
data type of the R-object becomes the data
type of the variable
Basic R Data Types
Numeric
– Decimals(e.g. 4.5) and integers(e.g. 4)
– e.g. my_numeric <- 12.5
Boolean values
– TRUE or FALSE
– e.g. my_logical <- TRUE
Text(string)
– Characters
– e.g. my_character<- „Thyolo‟
– Characters are closed in single(„‟) or double quotes(“”)
Basic R data types
To check the data type of a variable you use
the function class()
e.g. class(my_character)
R functions
A function is a set of statemnets organised together
to perform a specific task
An R function is invoked by its name, then followed
by the parenthesis and zero or more arguments
Example: function c which combines three numeric
values into a vector
– c(1,2,3)
Examples of built-in R functions:
– seq(), mean(), max(),print()
Examples of R built-in
functions
# Create a sequence of numbers from 1 to 1
seq(1:10)
# Find mean of numbers from 1 to 10
mean(1:10
# Find sum of numbers from 1 to 10
sum(1:10)
R packages
R packages are a collection of R functions,
compiled code and sample data
Are stored in under a directory called „library‟ in the
R environment.
A set of R packages is installed during R installation
More packages can be installed when needed for
specific purpose
Other packages which are already installed have to
be loaded before they are used in R
R Packages
library() # gets the list of all installed packages
[Link](“package name”) # install a
package from CRAN webpage
– e.g. [Link](“raster”) # install the package
named „raster‟
library(“package name”) # load the package
– e.g. library(raster) # load the package named
„raster‟
Install packages using Packages tab
Within the Packages tab,
you will see a list of
packages currently
installed on your
computer and two
buttons labeled either
“Install” or “Update”
Load packages using the Packages
tab
Check the box next to the package name
R data structures
Ways how data is represented in R
– Vector – a sequence of data elements of the same basic
type. Members in a vector are called components
– Matrix – a collection of data elements arranged in a 2-D
rectangular layout.
– List – an R-object which can contain many different types of
elements inside it such as vectors, functions or anther list
– Data frame – A list of vectors of equal length used for
storing data tables. Multiple columns and/or rows of data
and multiple types
Vectors
c() function is used to create vector
objects with elements separated by a comma
Vector arithmetic:
Reading data into R
Large data objects will usually be read as values from external files
rather than entered during
an R session at the keyboard
There are a number of functions which are used to read data into R
depending on the type of the data file
CAUTION: data should be in the working directory before it can be
read into R
Examples:
– To read csv data into R, the [Link]() function is used
– To read shapefiles into R, the st_read() function is used
– To read a single raster file, the raster() function is used
Reading data into R
Read gps_points csv file located in the
working directory:
Result:
Reading data into R
You can use
the File>Import
Dataset tab to
import text,
excel, spss, sas
or stata
GIS with R:
Tell the love story
Any questions?