Spatial Data Analysis with R
Society for Conservation GIS, July 2021

R Syntax

R as a Fancy Calculator

2 + 2      # add numbers
3 ^ 4      # powers
sqrt( 49 ) # functions

Run the commands above in the RStudio console.
How many decimals does R display by default?

White space is generally ignored in R (but helpful for readability).

Everything in R is case sensitive.

The # character tells R that what comes after is a comment.

Variables

A key technique in all programming languages is to store values in the form of variables.

In R, you can use the ‘=’ or ‘<-’ operators to do this.

## These are equivalent:
y <- 3^3
y = 3^3

RStudio keyboard shortcut to insert ‘<-’: alt + -

The term ‘variable’ and ‘object’ are generally synonymous.

Note when you assign a value to a variable, R doesn’t print the result to the console. To see the value of a variable, simply type it by itself.

Pretty much anything can be saved to a variable. Here we save some text and dates.

flv <- "vanilla"
flv
## [1] "vanilla"
start_date <- Sys.Date()
start_date
## [1] "2021-07-21"

Updating Variables

You can give a new value to a variable at any time.

You can use ‘current’ value as part of the expression for the ‘new’ value.

x <- 2
# x is now 2

x <- x + 3
# x is now 5

Naming Variables

The rules for naming variables are pretty flexible. You can use numbers, letters, and most special characters.

Rules to take note of:

Naming Styles

There are a handful of popular naming styles. Pick one that you like, and be consistent!

Style Example
alllowercase adjustcolor
period.separated shoe.size
underscore_separated (aka snake case) numeric_version
lowerCamelCase addTaskCallback
UpperCamelCase SignatureMethod

Data Types

All variables have a class or data type, which you can view using class().

num_plots <- 10
class(num_plots)
## [1] "numeric"

Other common data types:

Vectors

Most variables are vectors, in other words they can store multiple values. For basic data types, like numbers and characters, these are called vectors.

When we enter x <- 1, we are actually creating a numeric vector of length 1.

x <- 24
x
## [1] 24


rep() is a function that repeats a value, returning a vector:

y <- rep("ball", 5)
y
## [1] "ball" "ball" "ball" "ball" "ball"


rnorm() is a function that can generate multiple random numbers:

devs <- rnorm(5)
devs
## [1] -0.01511176  0.80493927 -0.14100897  1.28987350  1.51903961


c() stands for combine. It returns a vector containing the arguments passed (which all have to be the same type).

yn <- c(TRUE, FALSE, TRUE)
yn
## [1]  TRUE FALSE  TRUE


LETTERS is an example of a built-in constant. It contains a vector of length 26 containing characters:

LETTERS
##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

The [1] and [18] in the output tells you the index of the element displayed after it.

length(LETTERS)
## [1] 26

Filtering

To extract a single element from a vector, use square bracket notation. Inside the square brackets, put the index of the element you want.

LETTERS[2]
## [1] "B"

To return multiple elements, pass multiple indices.

LETTERS[2:4]
## [1] "B" "C" "D"
LETTERS[2:4]
## [1] "B" "C" "D"

You can also use square brackets to extract elements in a different order.

LETTERS[4:2]
## [1] "D" "C" "B"

Working with Functions

Many functions take arguments. Arguments can be required or optional.

See the function’s help page to determine which arguments are expected.

If you pass arguments to a function in the order expected and don’t skip any, you don’t have to name them:

rnorm(500, 50, 3)  ## generate 500 normally distributed random
                   ## numbers with a mean of 50 and stand dev = 3.

If you don’t pass arguments in expected order (or skip some), you have to name them in the parentheses:

rnorm(n=100, sd=0.3) ## generate 100 normally distributed random
                     ## numbers with stand deviation = 0.3

R Notebook Exercise

nb_syntax_scgis21.Rmd
Review R syntax

preview notebook | answer key

Future topics



Next: Working with Packages