R for Spatial Statistics

 

Getting Started

This lesson will get you started with syntax in R and a number of tips you'll need in the future. Check back with this lesson as you learn more about R.

Math and Variables In the Console

R can be used as a very sophisticated calculator. This tutorial will introduce you to simple variables and math in R.

Open R-Studio and click in the "Console". You can create new variables in R, set them to values, and then display them very easily. Enter the following text clicking "Enter" after each line.

x=100
x

The first line indicates that R should create a variable called "x" and set it to the value 100. The less than symbol followed by a dash ("<-") used to be the most common way to set variable values in R but equals ("=") is becoming more common. They are identical in function.

Note: There are a number of other ways to set variables but "=" is the most common and we'll use it throughout these tutorials.

The second line prints the variable. You can type the name of any variable at any time to see it's current value. In RStudio, variables are also available in the "Workspace" tab in the upper right panel.

R is a little different from other languages as you can use the period character (".") in variable names but this is not recommended as other languages typically use periods to dereference member variables and functions. Instead, I recommend using "Camel Case" variable names which are just like regular English text but without spaces. This will also make your code easier to read and support.

ModelSlope=0.4
ModelIntercept=12.2

R uses the dollar sign ("$") to dereference objects but we'll talk more about that when we look at tables in R.

Note: Many of the examples of R code will use very short variable names. I strongly recommend using descriptive variable names to make your code more readable.

Arithmetic

You can use traditional arithmetic operators in R. Try the following and print out the results each time.

x=10
y=12
z=x*y

There are a large number of mathematical functions that are available within R. Try some of the following.

Function Name Description
sqrt(x) Returns the square root of a value
log(x) Natural Log of X
log(x,base) Log with the specified base
log10(x) Log of base 10
log2(x) Log of base 2
exp(x) Raise x to the power of e
abs(x) Absolute value of x
sin(x) Returns the sine of x (x should be in radians)
cos(x) Returns the cosine of x (x should be in radians)
tan(x) Returns the tangent of x (x should be in radians)
asin(x) Returns the inverse (arc) sine of x (result will be in radians)
acos(x) Returns the inverse (arc) cosine of x (result will be in radians)
atan(x) Returns the inverse (arc) tangent of x (result will be in radians)
atan2(x,y) Returns the inverse (arc) tangent of x (result will be in radians), x and y are specified so the tangent returns an angle in the correct quadrant

 

Vectors

A vector in R is a linear sequence, or "set", of data values. One of the most powerful features of R is the ability to create and manipulate vectors. There are a large number of functions to create and manipulate data in vectors and other structures. You can also use traditional mathematical functions on vectors just like they were scalar values.

Try the code below and some other sequences.

x = 1:20 # set x to a sequence 1,2,3,4,5...20

You can now access each of the values in the vector with indexes:

x[1] # first entry
x[20] # last entry

Note that indexes for arrays in R go from 1 to N rather than from 0 to N-1.

The code shown below will extract four values from the vector we just created into a new vector.

y=x[5:10] # extract entries 5 through 10 
z=x[5:length(x)] # extract from the fifth through the end of the vector

In R you can also use the indexing above to set the values in a vector.

x[5]=0 # set the fifth entry to zero
x[10:20]=123 # set the tenth through twentieth entries to 123

You can insert and delete entries in vectors:

x=x[-1] # delete the first entry
x=append(y, FALSE, after=5) #   insert vector "y" into vector "x" at index=5 

You can use the mathematical operators we used above to work with vectors. You can also use the functions above and the ones below.

Function Name Description
mean(x) Returns the mean (average) of a vector
sum(x) Returns the sum of the values in a vector
length(x) Returns the length of a vector
identical(x,y) Returns true if the vectors are identical

Try writing some functions with vectors and make sure you feel comfortable creating vectors and changing their values.

One valuable function to create vectors is "seq()" for sequence. This function creates a sequence of values in a new vector. The parameters are a start value, an end value, and a length of the vector. "seq()" will create a sequence of values that are equally spaced in the vector.

x=seq(-4,4,length=200)

The function "c" is actually for "concatenate" but it can also be used to create new sequences of values as shown below:

x = c(1.4, 5.7, 2.4, 6.3, 22.6) 

Tips

arrow keys - recall commands

objects() # shows current objects (variables)

rm(<object name1>,<object name2>,...) # removes objects

; # separates commands

<esc> will get you out of the "+" mode

Tips for Using the Console.

If you use the R console outside of R Studio, you'll want to be able to "quit" the console.

q() # quit the console window 

Additional Resources

cbind(..., deparse.level = 1)  
rbind(..., deparse.level = 1)