Switch between the console and script editor with Ctrl + 1 and Ctrl + 2.
Scroll through the console history with ↑ and ↓.
Search the console history with Ctrl + r.
Clear the console screen with Ctrl + l.
(Optional) Pick a colour scheme in the settings.
Review the RStudio cheatsheet. What is the keyboard shortcut to comment (and uncomment) the selected text?
Using R as a calculator
Type at the console to answer the following questions.
What is \(5^7\)?
NoteSolution
5^7
[1] 78125
# Or, another way of writing this:5**7
[1] 78125
What is the area of a circle with radius 5cm?
NoteSolution
# We could have approximated pi, for example:3.14*5^2
[1] 78.5
# However, R has a built-in constant 'pi' object (see ?pi) that we can use# instead:pi *5^2
[1] 78.53982
And the circumference?
NoteSolution
2* pi *5
[1] 31.41593
Getting help
Check the help for the fivenum function.
What does the na.rm argument do?
How can you calculate the modulo of two numbers?
TipHint
The modulo is the remainder after division of one number by another; see here for details. You may need to search online to answer this question.
Creating objects
Define two new objects containing your first and last name as strings.
NoteSolution
# Example for my name:first_name <-"Ewan"last_name <-"Carr"
Use the paste command to concatenate these objects.
NoteSolution
paste(first_name, last_name)
[1] "Ewan Carr"
# Note that we haven't stored the result. R will print the output to the# console, but then forget the result. We need to assign the output to a# new object to store it in memory:full_name <-paste(first_name, last_name)
Repeat the calculation of the circumference of a circle. This time:
Define a new variable radius that contains the value 5.
Use this variable in your calculation.
NoteSolution
radius <-52* pi * radius
[1] 31.41593
TipReflection
What happens if you don’t assign something?
How can you tell what objects are currently assigned?
Practice using str and typeof to check the structure and types of the objects you just created.
NoteSolution
str(first_name)
chr "Ewan"
typeof(first_name)
[1] "character"
str(radius)
num 5
typeof(radius)
[1] "double"
Remove an object from memory using rm or via the RStudio “Environment” pane.
rm(first_name)rm(last_name)rm(radius)
Working with vectors
Create three vectors:
A sequence of numbers from 1 to 5;
The letters a, b, c, d, e;
Five random numbers.
TipHint
Use the functions c, seq, rnorm(5).
NoteSolution
# A sequence of numbersx <-c(1, 2, 3, 4, 5)x <-seq(1, 5, 1)x <-1:5# Letters a, b, c, d, ey <-c("a", "b", "c", "d", "e")y <- letters[1:5]# Five random numbersz <-rnorm(5)
Create two vectors, a and b, each containing 10 random numbers (using rnorm).
NoteSolution
a <-rnorm(10)b <-rnorm(10)
Add each value of a to the corresponding value of b, creating a new vector of length 10.