Check to make sure everyone has installed R and RStudio. Instructions here: https://ucsdlib.github.io/win2017-gps-intro-r/
Library Upcoming classes - workshop site http://ucsdlib.github.io/workshops/
collaborative note taking - notes will be up for later review - volunteers to start note taking
http://pad.software-carpentry.org/2017-gps-r
Red for help and questions Yellow for everything is good
Key lessons to take time on: Data subsetting - conceptually difficult for novices Functions - learners especially struggle with this Data structures - worth being thorough, but you can go through it quickly. go through examples of an R help page: help files can be intimidating at first, but knowing how to read them is tremendously useful.
Code and workflow are more reproducible if we can document everything we do. RStudio files can be saved and shared which enables replication of workflow and results.
This workshop will teach you how to start this process using R and RStudio. we’re going to teach you some of the fundamentals of the R language as well as some best practices for organizing code for scientific projects that will make your life easier. We’ll be using RStudio: a free, open source R integrated development environment. provides a built in editor, works on all platforms (including on servers) and provides many advantages such as integration with version control and project management.
R Studio Application overview: Main interface has 4 primary panes that make up the application
Console - is where R commands are where R code is processed.
This windows is where you can edit code lines or view data sets.
Shows your command history Environment
Plots and charts are displayed here. Installed Packages can be loaded Help information is also viewed here.
there are a 2 ways to interact with R
Show: Tools > Keyboard shortcuts help Alt+shift+k opt+shift+k (Mac) https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts
There are buttons, menu choices, and keyboard shortcuts.
To run the current line, you can
To run a block of code, select it and then Run. If you have modified a line of code within a block of code you have just run, there is no need to reselect the section and Run, you can use the next button along, Re-run the previous region.
This will run the previous code block including the modifications you have made.
Show Re-run button
We will be working primarily in the script editor window for this workshop.
very quickly here is an example of an R script that contains the primary R syntax.
show image in link
Review example script:
https://github.com/ucsdlib/intro-to-r/blob/gh-pages/challenges-images.Rmd
$ operator lets you access variables within a data set. [ dataset$variable]
Now that we have an idea of what a R script is composed of let’s begin with creating basic objects.
The simplest thing you could do with R is do arithmetic:
1+100
And R will print out the answer, with a preceding “[1]”.
Don’t worry about this for now, we’ll explain that later. For now think of it as indicating output.
if you type in an incomplete command, R will wait for you to complete it:
1 +
Any time you hit return and the R session shows a “+” instead of a “>”, it means it’s waiting for you to complete the command.
If you want to cancel a command you can simply hit “Esc” and RStudio will give you back the “>” prompt.
When using R as a calculator, the order of operations is the same as you would have learned back in school.
From highest to lowest precedence:
3+5*2
Use parentheses to group operations in order to force the order of evaluation if it differs from the default, or to make clear what you intend.
(3 + 5) * 2
This can get unwieldy when not needed, but clarifies your intentions. Remember that others may later read your code.
(3 + (5 * (2 ^ 2))) # hard to read
3 + 5 * 2 ^ 2 # clear, if you remember the rules
3 + 5 * (2 ^ 2) # if you forget some rules, this might help
The text after each line of code is called a “comment”. Anything that follows after the hash/pound symbol # is ignored by R when it executes code.
Really small or large numbers get a scientific notation:
2/10000
Which is shorthand for “multiplied by 10^XX”. So 2e-4 is shorthand for 2 * 10^(-4).
You can write numbers in scientific notation too:
5e3 # Note the lack of minus here
R has many built in mathematical functions. To call a function, we simply type its name, followed by open and closing parentheses.
Anything we type inside the parentheses is called the function’s arguments:
sin(1) # trigonometry functions
log(1) # natural logarithm
log10(10) # base-10 logarithm
exp(0.5) # e^(1/2)
Don’t worry about trying to remember every function in R.
You can simply look them up on Google, or if you can remember the start of the function’s name, use the tab completion in RStudio.
This is one advantage that RStudio has over R on its own, it has auto-completion abilities that allow you to more easily look up functions, their arguments, and the values that they take.
Typing a ? before the name of a command will open the help page for that command.
As well as providing a detailed description of the command and how it works, scrolling to the bottom of the help page will usually show a collection of code examples which illustrate command usage.
We can also do comparison in R:
1 == 1 # equality (note two equals signs, read as "is equal to")
1 != 2 # inequality (read as "is not equal to")
1 < 2 # less than
1 > 0 # greater than
1 >= -9 # greater than or equal to
Tip comparing numbers:
A word of warning about comparing numbers: you should never use == to compare two numbers unless they are integers (a data type which can specifically represent only whole numbers).
Computers may only represent decimal numbers with a certain degree of precision, so two numbers which look the same when printed out by R, may actually have different underlying representations and therefore be different by a small margin of error (called Machine numeric tolerance).
Instead you should use the all.equal function. Further reading: http://floating-point-gui.de/
We can store values in variables using the assignment operator <-, like this:
x <- 1/40
Notice that assignment does not print a value.
Check under Environment Tab.
Instead, we stored it for later in something called a variable.
x now contains the value 0.025:
x
Notice also that variables can be reassigned:
x <- 100
x used to contain the value 0.025 and and now it has the value 100.
Assignment values can contain the variable being assigned to:
x <- x + 1 #notice how RStudio updates its description of x on the top right tab
The right hand side of the assignment can be any valid R expression.
The right hand side is fully evaluated before the assignment occurs.
can contain letters, numbers, underscores and periods. They cannot start with a number nor contain spaces at all. Different people use different conventions for long variable names, these include:
What you use is up to you, but be consistent.
It is also possible to use the = operator for assignment:
x = 1/40
But this is much less common among R users.
The most important thing is to be consistent with the operator you use. There are occasionally places where it is less confusing to use <- than =, and it is the most common symbol used in the community.
So the recommendation is to use <-.
One final thing to be aware of is that R is vectorized, meaning that variables and functions can have vectors as values. For example:
1:5
2^(1:5)
x<-1:5
2^x
This is incredibly powerful; we will discuss this further in an upcoming lesson.
There are a few useful commands you can use to interact with the R session.
ls
will list all of the variables and functions stored in the global environment (your working R session):
ls()
Note here that we didn’t given any arguments to ls
, but we still needed to give the parentheses to tell R to call the function.
If we type ls
by itself, R will print out the source code for that function!
ls
You can use rm to delete objects you no longer need:
rm(x)
If you have lots of things in your environment and want to delete all of them, you can pass the results of ls to the rm
function:
rm(list = ls())
In this case we’ve combined the two. Like the order of operations, anything inside the innermost parentheses is evaluated first, and so on.
In this case we’ve specified that the results of ls should be used for the list argument in rm
.
When assigning values to arguments by name, you must use the =
operator!
It is possible to add functions to R by writing a package, or by obtaining a package written by someone else.
there are over 7,000 packages available on CRAN (the comprehensive R archive network).
go through examples of an R help page: help files can be intimidating at first, but knowing how to read them is tremendously useful.
R and RStudio have functionality for managing packages:
installed.packages()
install.packages("packagename")
, where packagename is the package name, in quotes.update.packages()
remove.packages("packagename")
library(packagename
)Create some variables and assign values. Then clean up your working environment by deleting the variables.
We can use the rm command to accomplish this task
E.g. rm(age, mass)
The scientific process is naturally incremental, and many projects start life as random notes, some code, then a manuscript, and eventually everything is a bit mixed together.
Then you end up with something like this:
Show image: http://swcarpentry.github.io/r-novice-gapminder/fig/bad_layout.png
There are many reasons why we should ALWAYS avoid this:
A good project layout will ultimately make your life easier:
Fortunately, there are tools and packages which can help you manage your work effectively.
One of the most powerful and useful aspects of RStudio is its project management functionality.
We’ll be using this today to create a self-contained, reproducible project.
We’re going to create a new project in RStudio:
Next create a data folder inside our project.
Now when we start R in this project directory, or open this project with RStudio, all of our work on this project will be entirely self-contained in this directory.
When working with data in RStudio, you should separate the original (raw) data from intermediate datasets that you may create for the need of a particular analysis.
for example, you could create the data directory - for your raw data create a data-output directory for working with intermediate data sets create a figure-output directory for the plots you will generate
Although there is no “best” way to lay out a project, there are some general principles to adhere to that will make project management easier:
This is probably the most important goal of setting up a project. Data is typically time consuming and/or expensive to collect. Working with them interactively (e.g., in Excel) where they can be modified means you are never sure of where the data came from, or how it has been modified since collection. It is therefore a good idea to treat your data as “read-only”.
In many cases your data will be “dirty”: it will need significant preprocessing to get into a format R (or any other programming language) will find useful.
This task is sometimes called “data munging”.
I find it useful to store these scripts in a separate folder, and create a second “read-only” data folder to hold the “cleaned” data sets.
Anything generated by your scripts should be treated as disposable: it should all be able to be regenerated from your scripts.
There are lots of different ways to manage this output.
I find it useful to have an output folder with different sub-directories for each separate analysis.
This makes it easier later, as many of my analyses are exploratory and don’t end up being used in the final project, and some of the analyses get shared between projects.
Good Enough Practices for Scientific Computing gives the following recommendations for project organization:
Download the gapminder data from here.
To make sure we have the right data, we can view the data:
* click data/ folder
* Click on gapminder-FiverYearData.csv
* Select view file
* In Console window you can see a new tab appear showing the data.
This is the data we will be working for this workshop later on.
?function_name
help(“function_name”)
Type in an example:
?vector
This will load up a help page in RStudio (or as plain text in R by itself).
Each help page is broken down into sections:
Different functions might have different sections, but these are the main ones you should be aware of.
Many packages come with “vignettes”: tutorials and extended example documentation. Without any arguments, vignette() will list all vignettes for all installed packages; vignette(package="package-name") will list all available vignettes for package-name, and vignette("vignette-name") will open the specified vignette.
If a package doesn’t have any vignettes, you can usually find help by typing
help("package-name")
When you kind of remember the function
If you’re not sure what package a function is in, or how it’s specifically spelled you can do a fuzzy search:
??function_name
If you’re having trouble using a function, 9 times out of 10, the answers you are seeking have already been answered on Stack Overflow or use Google search
You can search using the [r] tag.
If you can’t find the answer, there are a few useful functions to help you ask a question from your peers:
?dput
Will dump the data you’re working with into a format so that it can be copy and pasted by anyone else into their R session.
sessionInfo()
Will print out your current version of R, as well as any packages you have loaded. This can be useful for others to help reproduce and debug your issue.
In the next lesson we’ll be taking a look at Data Structures.