8 * 3[1] 24
In this activity we’ll start to learn how to work with R and explore some of the syntax and functions that we encountered in the video.
We enter commands at the prompt > in the R Console. R then
For example, in the code block below we run multiply two numbers
R prints the result because we did not assign the output to an object.
We can assign the output to an object using the <- assignment operator. In the block below, we repeat the multiplication but this time we assign the output to an object named answer
Now R doesn’t print anything. To retrieve the answer to our multiplication we must type the name of the object and hit Enter
At the most basic level, we create vectors by combining elements together using the c() function. For example, to create a vector of five numbers we use
What kind of vector is v?
v is a numeric vector.
This was a bit of a trick question! If you said "numeric" then you were correct. It doesn’t matter that we combined integers (whole numbers) when creating the vector, R treats them as potentially have decimal places.
We can find out what R thinks any object is using the class() function:
But this doesn’t tell us the whole story. R distinguishes between different kinds of numbers. If we use typeof() we see that R thinks v is a double numeric vector (it is stored to double precision)
You or I might call the numbers in v integers or “whole numbers”. But R doesn’t store them this way. We can check if R thinks v is an integer (as a human would) using the as.integer() function:
If you want to insert integers, you need to add L after each number:
We can also coerce a numeric vector to an integer one using as.integer()
But beware what happens if you coerce numbers that are not integers this way
Create a vector named primes that contains the first 5 prime numbers.
Create a vector named fib that contains the first 10 Fibonacci numbers.
We can create other types of vector; we discussed
logical vectors, and
character vectors
in the video.
We create a logical vector by combining the elements TRUE and FALSE;
More conveniently, we can create a logical vector through the application of a Boolean operator. For example if we run
what we get back is a logical vector where the elements are TRUE if the Fibonacci number is greater than 3, and FALSE otherwise.
Create a vector named prime_10 that contains the first 10 prime numbers. Then create a logical vector that indicates if each of the primes is less than 17.
Character vectors are created by wrapping the elements in single or double quotes 'a', or "b". Double quotes " are preferred as they are slightly easier to read in code.
We create a character vector like any other using c()
We always enter quotes in pairs; the RStudio IDE will help you in this regard as it will automatically add the closing quote for you when you type the first one.
If you ever get stuck because you forgot to close a quote, click in the R Console window and hit the Esc key to get back to your prompt
Create a character vector named my_group that contains the first name of each member of your group, including your own.
rep() and seq()We can create sequences of numbers using the seq() function and the : operator. 1:10 is shorthand for seq(from = 1, to = 10, by = 1L).
To create a sequence of numbers from 5 to 14 we could use
or
Create a vector named my_seq containing the integers -4 – 9.
Create a vector named countdown containing the integers 10 to 0.
We can make more complex sequences using other arguments to seq(): by and length.out
We usually shorten the length.out argument name to just length.
To create a vector of first 10 positive odd numbers, we could use
Note that we don’t have to use both from and to when we call seq().
Create a vector named x that contains 15 evenly-spaced numbers between -4 and 20.
Create a vector named tens that contains every ten between 10 and 140
The rep() function allows us to create patterned vectors where we repeat the elements of one vector to create a longer vector. The key arguments are each and times, but there is also the length.out argument too.
Let’s start with a vector base with the following elements
If we want to repeat this vector 3 times, we would use
whereas, is we wanted to repeat each element of base 3 times, we would use
To repeat a vector until it has the desired length, we can use the length.out argument
Notice how we get an incomplete final replicate of base because 3 elements to not divide into 10 cleanly.
How you you repeat each element of the Fibonacci number vector fib twice?
Create a vector that repeats the first 10 primes 4 times.
We can subset vectors in one of several ways. The most common way is to specify the indices of the elements you want to return using a numeric vector. For example, to select the third prime number from our vector of the first 10 primes we would use
What is the 5th Fibonacci number in fib?
What is the 9th Fibonacci number in fib?
We can use negative number to exclude elements, for example
Subset the vector of Fibonacci numbers fib to return only the even elements
Subset the vector of Fibonacci numbers fib to exclude the odd elements
Logical vectors are handy ways to subset vectors. For example, if we have a vector 1:10, we can select the even elements using
[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
[1] 2 4 6 8 10
The %% operator is a new one for us. It is the modulo operator, and, given two numbers a and b returns the remainder of the division of a by b. Often we write this as “a mod b”. The definition of an even number is that when it is divided by 2 there is zero remainder. Hence we compute the remainder when dividing by 2 and compare (==) that with 0.
How would you create a vector containing all the odd numbers between 42 and 121?
We don’t have to create all the intermediary steps shown in the solution. We could just as easily do
[1] 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79
[20] 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117
[39] 119 121
at the expense of being a little harder to read and understand if you are new to R coding.
Say you have a vector containing the first n Fibonacci numbers, but you can’t remember how many of the Fibonacci numbers are in your vector. You do know that the vector is named fib, that the elements are in increasing order. You want to know which is the largest Fibonacci number in your vector. How would you do this?
Functions are a collection of R statements (lines of code) that are bundled together to complete a specific operation. In the video we encountered several functions.
We used the length() function and sum() was used to sum a vector of numbers. R contains many more simple functions like this:
max()min()log()exp()sqrt()mean()median()range()IQR() (inter-quartile range)What is the sum of the first 10 prime numbers?
What is the product (the value you get by multiplying all the values ina vector together) of the first 10 Fibonacci numbers?
One of the functions we used was runif(), to generate random numbers. By default the numbers lie between 0 and 1. If we run the functions multiple times we will get different sets of random numbers
[1] 0.6215656 0.7616534 0.3545634 0.4557839 0.8030921 0.7046027 0.3922859
[8] 0.3100442 0.6564782 0.4296959
[1] 0.9147179 0.2268405 0.6978093 0.7400072 0.9529051 0.7296110 0.2947730
[8] 0.8483208 0.6642853 0.4964112
We can use the set.seed() function to make the values returned by R’s random number generator repeatable
[1] 0.9148060 0.9370754 0.2861395 0.8304476 0.6417455 0.5190959 0.7365883
[8] 0.1346666 0.6569923 0.7050648
[1] 0.9148060 0.9370754 0.2861395 0.8304476 0.6417455 0.5190959 0.7365883
[8] 0.1346666 0.6569923 0.7050648
Using the seed 65, set the seed and then identify the largest (in value/magnitude) number in vector returned by
[1] 0.457741776 0.719112252 0.934672247 0.255428824 0.462292823 0.940014523
[7] 0.978226428 0.117487362 0.474997082 0.560332746 0.904031387 0.138710168
[13] 0.988891729 0.946668233 0.082437558 0.514211784 0.390203467 0.905738131
[19] 0.446969628 0.836004260 0.737595618 0.811055141 0.388108283 0.685169729
[25] 0.003948339
A related function is sample(), which at it’s most simplest, it randomizes a vector that you pass it.
Again, we need to set a seed if we want to make the randomization repeatable
[1] "g" "c" "h" "j" "b" "i" "a" "f" "e" "d"
[1] "g" "c" "h" "j" "b" "i" "a" "f" "e" "d"
We don’t need to just randomise with sample(), we can ask it to return a random sample of a few of the values. Say we want to return a random sample of size 10 from the letters of the English alphabet. We would use
Create a vector of the first 1000 positive integers. Using the seed 84, take a random sample of 50 of these numbers. Answer the following questions
Think about your answers to all of these questions and write the necessary code, before looking at the solution below. You may need to use the help system to find which function implements a particular mathematical operation.
[1] 943
[1] 11
[1] 474.5
[1] 491.36
[1] 24568
[1] 391
[1] 797
[1] 32
[1] 0
[1] 513.75
How many did you get right?
Work your way through the following questions to test your growing knowledge of R.
Determine the value of \frac{1.35^2 + 4.2^3}{4}.
Note that we use the ^ operator to raise a number to a power, e.g. 2^3 for 2 cubed.
You want to divide the number 4 by 2. What R code would you use to achieve this?
What is the average (mean) of the values c(34, 12, 5, -10)?
What is the median (the middle value if we order the values from smallest to largest) of the values c(1, 8, 100, 10000, 342, -125, 5, -10)?
What does the function rnorm() do?
How many arguments does the rt() function have?