Coding is a key skill for modern scientist and people who work with data. It allows us to write down what we want to do to a dataset (we call these instructions ‘scripts’), then execute our instructions. Importantly, the scripts we make can be shared with other people, who can run our code, check for mistakes, and build on our work. Compare this with other ways to work with data, such as excel, minitab, or SSPS, which are ‘point and click’. In these programs it is difficult to communicate efficiently how you have run an analysis.
There are many types of coding languages out there. The most useful and relevant for us, and others who work with data, is R. This is a coding language designed to work with data, officially called an object-based programming language, because it implements functions on objects (our data).
R is an open-source program built for data scientists by data scientists. The reproducibility of R, the fact that it is free and open source, and the speed at which we can see the step-by-step process of someone’s work is why universities now emphasise the teaching of R, over ‘point and click’ alternatives.
Learning to code can be a daunting task and it can feel like there is a huge learning curve ahead. In my experience, this coding anxiety is the biggest barrier to learning to code. Alongside showing you how to use R, I want to bust this anxiety, and turn you into a confident coder.
Coding is doable, useful, and sometimes frustrating. You dont need to be an Einstein to become a good coder.
In this session we will be exploring how to work with R. I do not expect you know everything about each topic we cover in this session. Instead, I hope you will get the lay of the land, understand what stuff R is capable of, and get you to start independently solving coding problems.
Our learning goals are:
Become familiar with the use of scripts for writing and saving your code.
Learn some basic coding etiquette and how to set up a project and scripts in R.
Be aware of packages and the R ecosystem.
Learn the basic concepts behind: running code - Loading different data types - Viewing data and exploring data structures - creating objects - Functions - data visualization
R scripts are the default way many people write their code. You can run your code line by line by clicking on the line, then pressing CTRL+ENTER.
Every line you run in the script is passed to the console where the command is implemented. You can write commands directly into the console but this is not ideal because your coding wont be saved.
We use Rstudio which is a wrapper for the base R programmer. Rstudio has more bells and whistles and makes coding a much more enjoyable experience. The default set up has four windows. Your scripts and console on the left (scripts up top and console beneath). The top right panel keeps track of the objects you have made and the history of the console. The bottom right panel shows your computer files, the inbuilt helper, a document viewer, a plot viewer, and a list of the packages installed on your computer.
Load the example script from the R101 folder and have a play around with it. Run the code line by line by pressing ctrl enter or run the entire thing. At this stage you don’t need to understand what each line of code does. But spend some time looking at the structure of the code and try and track what the script is doing to the data.
Now, make a new script, name it and save it some place sensible. It’s time to write your own code!
(Note: you can copy the following code into your own script, or write it out yourself.)
You are always coding with at least on other person, future you! So it is crucial to keep scripts neat and informative. A great way to do this is to add comments through the script. Any text with a hashtag # in front is read as a comment by R, and wont be run as code.
Good etiquette when setting up a script:
name it sensibly
comment, using #, what this script does, who wrote it and when
you can make subsections by using #### Title of subsection #### to keep things neat.
Now lets run some code.
Remember that R is an object based programming language. We can assign and create objects easily using an arrow <- or =
my_object <- 5 # look at the environment tab. It is keeping track of our objects
# or by using =. It is best practice to use <- to assign objects because = is used for lots of other functions and it can get confusing
my_object = 6
# lets check out the object we made. We can call an object using a function, or just running the name of the object. To look at what the function does, you can search for it in the help bar. Top tip: highlight a function and press F1 will also bring up the documentation for a function.
print(my_object)
## [1] 6
#or alternatively
my_object
## [1] 6
So our object is now the number 6. Note that the order you run code in is important. my_object did have the value of 5 but this was overwritten by the next command. Usually we run code top down, but in R we can chose to run lines of code independently. If you do this you need to be cautious and keep track of your objects. Many strange errors can occur if your run code out of order.
The naming of objects is important. Make sure the name is clear and informative. “test_1” is not a useful name and will lead to confusion. Also, R doesn’t like spaces, so by convention we use underscores instead.
Functions are things that modify/act on objects. There are many
1000’s of R functions. They always have this form:
function_name(an_object) Functions usually produce output
which is shown in the console. To capture this output to use later we
need to assign it to an object.
’an_object_changed_by_a_function <- function_name(an_object)`
Sometimes we don’t need to keep the output of function - it depends on what the function does.
To see how a function works we can type its name into the help tab in the bottom right window. Or an easier way to is to highlight the function name and hit F1 - this will pull up the help documentation automatically.
Every object we make has a STRUCTURE type. We can check this using the str() function
str(my_object)
## num 6
#in the console it tells us my_object is numerical with the value of 6
#We can store characters in objects too
my_text_object <- "six"
str(my_text_object)
## chr "six"
There are LOTs of types of data structures in R. This is R’s way of knowing how to treat objects.
We can have geometry structure for shapefiles, date and time structures for calender dates, and raster structures for pictures.
You will deal with lots of different data structures as you progress with R. However, there are some key structures you should understand now. Vectors and Data Frames.
Vectors are strings of values. Like 1, 2, 3, 4 ,5.
my_vector_object <- c(1,2,3,4,5,6,7,8,9,10)
#a short hand way of doing this is
my_vector_object <- c(1:10)
#we can ask how many variables our vector contains.
length(my_vector_object)
## [1] 10
Data frames are composed of multiple vectors. This data form is most similar to a basic table.
my_vector_2 <- c(3,5,8,2,6,5,4,3,2,1)
my_data_frame <- data.frame(my_vector_object, my_vector_2)
print(my_data_frame)
## my_vector_object my_vector_2
## 1 1 3
## 2 2 5
## 3 3 8
## 4 4 2
## 5 5 6
## 6 6 5
## 7 7 4
## 8 8 3
## 9 9 2
## 10 10 1
Note that the order of each vector is preserved in the data frame.
We can access specific parts of our data frame in a number of ways, formally this is called subsetting. The operators we use are called accessors. The accessor $ pulls out (or calls) one vector by name. The [] calls out one element by specifing its position in the data, in a vector this will pull out one value, in a data frame it will pull out one column. Unlike $, it will pull out a data frame composed of one vector, opposed to the vector its self. Subsetting is really useful, but can be a bit confusing! You will get more experience with this as you work with data.
my_data_frame$my_vector_object
## [1] 1 2 3 4 5 6 7 8 9 10
my_data_frame[1]
## my_vector_object
## 1 1
## 2 2
## 3 3
## 4 4
## 5 5
## 6 6
## 7 7
## 8 8
## 9 9
## 10 10
my_vector_2[2]
## [1] 5
Task: use the function mean() to find the average of
my_vector_2
Task: we can add a new column to a data frame like this
dataframe$new_col_name <- values_for_new_col. Using
subsetting, can you add a column to my_data_frame that is the sum of
column 1 and 2?
R can also make quick plots of data
plot(my_data_frame) #a scatter plot
hist(my_data_frame$my_vector_2) # a histogram
R comes pre-loaded with some core ‘base’ functions. You can do a lot with base R, but not everything. To add additional functions to R we need to download packages.
A package is a downloadable set of functions that has been created by someone else. They are always free. Officially vetted packages live in an archive called CRAN - The comprehensive R Archive Network.
It is super easy to download packages from CRAN.
to do so we use the function `install.packages(“Package name”). Here we will download a nifty package called mapview that lets up interact with spatial data in Rstudio.
#remember to remove the # before you run this.
#install.packages("mapview")
Once installed, we need to load the package into our library. The
library is where our downloaded packages live, and to use them in a
script we need to ‘check out’ specific packages. We do this with the
function library().
It is good coding etiquette to load all the package you need for an analysis at the beginning of the script. This keeps your code neat and allows other users to identify if they need to download any packages to run your script.
Lets load the package mapview and have a look at some data that comes with the package - German brewery locations.
library(mapview)
mapview(breweries)
So far we have only made our own data in the above code. We also need to know how to bring in external data.
We load in external data by providing a file path to a function in R. There are different functions for importing different data types.
For tabular data that you can open in excel we can use the function read.csv(). CSV stands for comma separated values and is the simplest format to store tabular data.
One quirk with R is that its doesn’t like \ in path
names. You must provide / instead.
Lets load in some climate data for BC cities. You need to insert the path to your data in read.csv()
climate_data <- read.csv("W:/work/users/ccosgrove/R_training/climate_data/climate_data.csv")
head(climate_data) #head() lets us peek at the first few rows of our table.
## X City province_id province_name population density MAP_2070 MSP_2070
## 1 1 Vancouver BC British Columbia 2426160 5749.9 3344.044 642.9586
## 2 2 Surrey BC British Columbia 568322 1797.9 4353.831 853.3572
## 3 3 Victoria BC British Columbia 363222 4722.3 1093.480 146.6107
## 4 4 Burnaby BC British Columbia 249125 2750.7 4079.780 797.3206
## 5 6 Kelowna BC British Columbia 181380 682.4 629.093 215.6971
## 6 8 Coquitlam BC British Columbia 148625 1216.7 4487.438 876.9100
## SHM_2070 Tave_2070 MAP_1961 MSP_1961 SHM_1961 Tave_1961 MAP_1981
## 1 53.52665 9.389368 3780.5566 700.2007 42.08823 5.612553 3765.7388
## 2 25.97177 7.982947 4888.7192 949.3941 19.09126 4.249711 4887.9365
## 3 154.44582 13.321420 1293.2592 149.0558 125.82781 9.526193 1189.2557
## 4 31.91632 8.333683 4588.6475 881.5994 24.07138 4.585564 4586.3037
## 5 96.40259 7.228793 643.6904 245.3070 67.86209 3.817072 746.2382
## 6 21.30197 7.787746 5034.1387 979.7980 15.02300 4.070662 5029.3462
## MSP_1981 SHM_1981 Tave_1981 x y
## 1 1014.2657 27.35321 5.827588 -123.1055 49.20945
## 2 1342.4958 13.23663 4.500459 -122.8555 49.20945
## 3 233.3181 79.46325 9.648352 -123.3555 48.45948
## 4 1255.3337 16.26621 4.827135 -122.9388 49.29278
## 5 343.0065 48.35071 3.993343 -119.5223 49.87609
## 6 1378.5758 10.89316 4.331462 -122.7722 49.29278
#To view the entire dataframe use:
#View(climate_data)
str(climate_data)
## 'data.frame': 120 obs. of 20 variables:
## $ X : int 1 2 3 4 6 8 9 12 13 15 ...
## $ City : chr "Vancouver" "Surrey" "Victoria" "Burnaby" ...
## $ province_id : chr "BC" "BC" "BC" "BC" ...
## $ province_name: chr "British Columbia" "British Columbia" "British Columbia" "British Columbia" ...
## $ population : int 2426160 568322 363222 249125 181380 148625 117735 106079 97902 90990 ...
## $ density : num 5750 1798 4722 2751 682 ...
## $ MAP_2070 : num 3344 4354 1093 4080 629 ...
## $ MSP_2070 : num 643 853 147 797 216 ...
## $ SHM_2070 : num 53.5 26 154.4 31.9 96.4 ...
## $ Tave_2070 : num 9.39 7.98 13.32 8.33 7.23 ...
## $ MAP_1961 : num 3781 4889 1293 4589 644 ...
## $ MSP_1961 : num 700 949 149 882 245 ...
## $ SHM_1961 : num 42.1 19.1 125.8 24.1 67.9 ...
## $ Tave_1961 : num 5.61 4.25 9.53 4.59 3.82 ...
## $ MAP_1981 : num 3766 4888 1189 4586 746 ...
## $ MSP_1981 : num 1014 1342 233 1255 343 ...
## $ SHM_1981 : num 27.4 13.2 79.5 16.3 48.4 ...
## $ Tave_1981 : num 5.83 4.5 9.65 4.83 3.99 ...
## $ x : num -123 -123 -123 -123 -120 ...
## $ y : num 49.2 49.2 48.5 49.3 49.9 ...
It can get tiring writing out long path names. To get around this we
can set a working directory. The working directory becomes the default
place R looks for a file. Any file within the working directory just
needs to be called by name for example
climate_data <- read.csv("climate_data.csv") I prefer to
use the full path name, especially on shared servers. This way I can
share my code and it should run on a co-workers machine straight
away.
TIP: You can set your working directory using the function setwd() or by going to the session tab found at the top of Rstudio. If you have created an R project first, then made a new script in this project, the location of the project folder becomes the default working directory.
If you are new to R, feel free to step away from your code and digest what we have just covered. A non-coding task that’s useful is to explore the range of packages that are out there. Some cool ones to look are are lidR, rayshader, cowsay (a fun package). There is also a BCdata pacakge.
Also take a look at the www.data-to-viz.com/ website. R is great for making data visualization and this website has many examples of cool charts and plots.
Your challenge is to find out what city is expected to see the greatest increase in average temperature (Tave) compared to 1961 conditions?
AND
By investigating MAP - mean annual Precipitation (mm) - what cities are expected to get wetter and what cities are expected to get drier compared to 1961?
The following functions may be useful
#in the package dplyr
slice_max()
slice_min()
mutate()