Introduction to RStudio
Finding your way around RStudio
Last updated
Finding your way around RStudio
Last updated
Throughout this lesson, we're going to teach you some of the fundamentals of the R language as well as some best practices for organising code for scientific projects that will make your life easier using RStudio: a free, open source R integrated development environment. It 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.
When you first open RStudio, you will be greeted by three panels:
The interactive R console (entire left)
Environment/History (tabbed in upper right)
Files/Plots/Packages/Help/Viewer (tabbed in lower right)
Once you open files, such as R scripts, an editor panel will also open in the top left, and your console will be visible in the bottom right, like this:
In the lower left portion of RStudio, you'll find the R interactive console. This is where you will run all of your code, and can be a useful environment to try out ideas before adding them to an R script file. This console in RStudio is the same as the one you would get if you opened the R application or you just typed in R
in your command line environment.
The first thing you will see in the R interactive session is a bunch of information, followed by a ">" and a blinking cursor. The console operates on the idea of a "read, evaluate, print loop"
You type in your commands and hit enter.
R reads and interprets what you've written and tries to execute it.
R prints a result to the console.
There are two main ways one can work within RStudio.
Test and play within the interactive R console then copy code into a .R file to run later.
This works well when doing small tests and initially starting off.
It quickly becomes laborious.
Start writing in an .R file and use RStudio's command / short cut to push current line, selected lines or modified lines to the interactive R console.
We recommend taking approach number 2 for most applications. Let's go ahead and make a new .R script file by clicking the little page icon in the top left corner, and selecting R script from the dropdown menu. An R script is basically a text file with R commands.
RStudio offers you great flexibility in running code from within the editor window. There are buttons, menu choices, and keyboard shortcuts. To run the current line, you can:
Click on the Run
button just above the editor panel.
Select "Run Lines" from the "Code" menu.
Hit Ctrl-Enter
in Windows or Linux or Command-Enter
on OS X. (This shortcut can also be seen by hovering the mouse over the button).
Hint: You can also run multiple lines by selecting them and then running your code using 1, 2 or 3.
With that, let's start having a play in the R console!
The simplest thing you could do with R is do arithmetic. Try typing into the console:
Now hit ENTER
. R should return:
You should see 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. Try typing this:
At this stage R is effectively waiting for you to complete the command. R lets you know this by showing you a +
sign rather than the usual >
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, forgetting whatever you'd input beforehand.
Try canceling the command.
When using R as a calculator, the order of operations is the same as you would have learnt back in school.
From highest to lowest precedence:
Parentheses: (
, )
Exponents: ^
or **
Division: /
Multiplication: *
Addition: +
Subtraction: -
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.
is not the same as
This can get unwieldy when not needed, but clarifies your intentions. Remember that others may later read your code.
While talking about readable code, make use of comments to show what a line is doing
The text after each line of code is called a comment. Anything that follows after the hash symbol #
is ignored by R when executes code.
When returning really small or large numbers R will eschew a bunch of zeroes in favour of scientific notation:
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:
We can also do comparisons in R:
Now that you're familiar with the fundamentals, here are a few challenges to test what you've learned.
Using functions and finding help
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.
Here are just a few of the functions R has on offer.
Don't worry about trying to remember every function in R. You can simply look them up on google, or you can find help in RStudio!
When you start typing a function in RStudio, it will show a list of possible functions alongside what you're writing.This is one advantage that RStudio has over R on its own, it has autocompletion 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'll go through an example later.
Instead of typing out numbers we might want to use in calculations again and again, we can store their values in variables using the assignment operator <-
, like this:
Notice that assignment does not print a value. Instead, we stored it for later in something called a variable. frequently_used_number
now contains the value 0.025
:
More precisely, the stored value is a decimal approximation of this fraction called a floating point number.
You can also assign variables using =
Look for the Environment
tab in the top right pane of RStudio, and you will see that frequently_used_number
and its value have appeared. Our variable frequently_used_number
can be used in place of a number in any calculation that expects a number:
Notice also that variables can be reassigned:
frequently_used_number
used to contain the value 0.025 and and now it has the value 100.
Assignment values can contain the variable being assigned to:
When naming variables, you need to follow a few rules:
Variable names can contain:
letters
numbers
underscores
periods.
They cannot start with a number
They cannot have any spaces.
Different people use different conventions for long variable names, these include:
underscores_between_words
periods.between.words
camelCaseToSeparateWords
What you use is up to you, but be consistent, and remember that you're likely going to be typing these out quite a few ties, so try to be concise too.
One final thing to be aware of is that R is vectorised, meaning that variables and functions can have vectors as values. For example
You can create vectors using the c()
function
This is incredibly powerful, but we will discuss this further in a later 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):
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!
You can use rm
to delete objects you no longer need:
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 to do a big spring clean of your environment.
In this case we've combined the two. Just 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 thelist
argument in rm
. When assigning values to arguments by name, you must use the =
operator, not the <-
operator from before.
It is possible to add functions to R by writing a package, or by obtaining a package written by someone else. As of this writing, there are over 15,000 packages available on CRAN (the comprehensive R archive network). R and RStudio have functionality for managing packages:
you can see what packages are installed by typinginstalled.packages()
you can install packages by typing install.packages("packagename")
where packagename
is the package name, in quotes. Remember, this is what we did when installing the tidyverse on the setting up page earlier
you can update installed packages by typing update.packages()
you can remove a package with remove.packages("packagename")
and most importantly, you can make a package available for use with library(packagename)
, without doing this you won't be able to use the contents of the package in the current session
Note that a package has to be installed only once. However, it must be called every time you open R or RStudio by typing
Here's one last fun challenge for the lesson