Introduction to R
Introduction
Now that we’ve reviewed the foundational mathematics skills, we are going to get started on
our R journey! In this Module, we’ll introduce the syntax for several different operations in R; a
syntax is the way we structure our typed code in order to get R to carry out our work for us.
This Module will build on the skills covered in the previous Module, by translating the
foundational concepts of arithmetic into the R coding language.
By the end of this module, you’ll be able to:
1. Operate within the R environment
2. Perform basic arithmetic using R
3. Assign variables and manipulate them
4. Create small data sets known as vectors
5. Evaluate these vectors using functions
6. Use R to generate plots
So let’s open R and get started!
Time: 1:25
Concept 1: The Command Prompt
Opening R will start a new R session. You’ll see a rectangular application window
probably populated with a block of text. At the bottom, you’ll see the command prompt >.
Figure: Empty Command Prompt upon starting a new R session.
This is your interface. Think of R as a simple calculator, and try executing a simple math
problem. Go ahead and type something into the command prompt. Suppose I wanted to know
the combined weight of two 6-month-old babies, one a boy and one a girl. If a typical 6-month
old boy weighs 7.9 kg, and a typical 6-month old girl weighs 7.3 kg, then their combined weight
can be computed by typing
7.9 + 7.3
Figure: Setting up an addition of two bodyweights for a typically-developing babies (kg units)
To make R calculate this expression, hit <ENTER> (or <RETURN>).
Figure: Executing the addition of two bodyweight values by hitting <ENTER>
Congratulations! You’ve just entered your first command into R! Hopefully it gives you a
reasonable answer.
Concept 2: Arithmetic
2.1 Elementary Operations
Subtraction is similar. Suppose that instead of wanting to know the combined weight of two
babies, we wish to know the difference in weight between the boy and the girl. Type
7.9 –dash- 7.3 <ENTER>
into the command prompt, and get the proper value in response.
Figure: Subtraction of baby bodyweights via dash -.
In Module 2, we learned that there are multiple ways to express division. In R, there is
only one way: the forward slash /. According to UNICEF, nearly 400,000 babies were born on
New Year’s Day this year. Given that there are 24 hours in each day, we might ask: how many
babies were born per hour on that day?
We set up the calculation
400000 -forward slash- 24
Figure: Division via forward slash / in order to estimate the number of babies born per hour on
New Year’s Day.
Likewise, there is only one way to denote multiplication: the star or asterisk *. Suppose
that instead of the combined weight of a boy and a girl, we have two boys. Their combined
weight would be given as
2 -asterisk- 7.9
Figure: Multiplication via asterisk * in order to compute the combined weight of two baby boys.
2.2 Compound Expressions
In Module 2, we learned about compound expressions being those with multiple
operations. We also learned about PEMDAS, where expressions with parentheses are executed
first, then exponents, multiplication, division, addition and subtraction. We could force the
operations by inserting parentheses as indicators of precedence. R obeys this convention:
Suppose we type
2*(7.9+7.3)
This would tell us the combined bodyweight of two sets of (a baby boy plus a baby girl).
Alternatively, suppose we typed
(2*7.9)+7.3
This would tell us the combined bodyweight of two boys plus one girl.
Figure: Demonstration of R’s obedience of the PEMDAS precedence for parentheses ( ).
Because R obeys PEMDAS, it computes these expressions differently.
…And likewise, if there are no parentheses, R will look for Exponents, Multiplication,
Division, Addition and Subtraction, in that order.
Figure: R obeys the conventional Order of Operations (PEMDAS).
As you can see, multiplication was executed first, then addition: multiplying 2*7.9, then adding
7.3.
Concept 3: Exponents
3.1 Powers
The first power we saw in Module 2 was the special case of the square, a value raised to
the power of 2. In R, the power is indicated via the carat, which you get by pressing the 6-key
whilst holding your shift key (Shift-6): ^.
Let’s try this on a square, which is a number multiplied by itself.
Type in
172.3 -carat- 2 <ENTER>
You’ll get 29687.29. Now let’s verify that with standard multiplication
172.3 -asterisk- 172.3 <ENTER>
Also yields 29687.29
Figure: Power of 2, i.e. square (denoted via carat ^). Yields same result as value multiplied by
itself.
Now let’s incorporate this power operator into a compound expression. The formula for Body
Mass Index is: Weight (in kilograms) divided by the square of height (in centimeters), multiplied
by 10,000.
So suppose we had a person weighing 69.2 kg, with a height of 172.3cm. We might calculate
their BMI as
<left parenthesis> 69.2 <forward slash> 173.2 <carat> 2 <right
parenthesis> <asterisk>10000
The resultant BMI is 23.3.
Figure: Calculating BMI using a compound expression involving a power.
Notice that R seamlessly executed this calculation in the PEMDAS framework: it found the
parenthetical expression, evaluated the exponent first, then the division, and then outside of
the parentheses, it carried out the multiplication.
And by the way, if you’d like to check your work, you can do so by opening the
NHANES_sample dataset posted with Module 5: this the BMI indicated for survey sequence
number 62161, in the first data row of the spreadsheet.
3.2 Scientific Notation
The syntax for multiplication and exponents are used together to convey numbers in
scientific notation. For instance 386,000 babies born on a given day can be written as 3.86×105.
The translation into R is the same as described above: substitute * for × and indicate the
exponent with carat ^:
Figure: Scientific notation using multiplication * and exponent ^.
Note that in R, we do not delimit thousands with commas; we just type the number into R
without any delimiters. We’ll see commas later (in sets!).
Likewise, 172.3 centimeters can be expressed as both 1.723 meters and 1.723×10-2 meters:
Figure: Scientific notation for small quantities use negative exponents.
Here again, PEMDAS is obeyed: R executes the exponent before the multiplication.
Note also that R allows for a convenient short-hand: the letter ‘e’, when placed between two
numbers is interpreted as ‘ten-to-the’. So 1.723 times ten to the minus two can be written as
1.723-e-minus-two.
Figure: Scientific notation using e as a short-hand for a power of ten.
You can type this directly yourself and get the same result. It will save you a few keystrokes.
Concept 4: Variables
4.1 Assignment
In coding, the word “variable” has a special meaning: it’s an object that you create so
that you can do work with it. We create a variable by making an assignment. A variable can
have any name, and can include letters, numbers, or underscores, but must start with a letter.
To define the variable, we type into the command prompt as follows: <variable name> <equals>
and then <value>. Let’s see an example from the previous section on BMI:
Let’s create a variable to store body weight. Let’s call the variable wt (for weight) and set it
equal to the value 69.2. Type
wt <equals> 69.2
Figure: Declaring a variable in R via the equals sign =.
Note that when you define a variable in R, R will remain quiet at the command prompt. This is
unlike our use of R to this point: when we were using R as a calculator, everything we typed at
the command prompt yielded a response from R. When we create a variable, that response is
suppressed. If you want to see the value for this variable, call for it by typing the variable name
at the command prompt
Figure: Verifying a variable’s value at the command line by typing the variable name and
<ENTER>
4.2 Vectors
We can create variables with more than a single value; these are known as vectors, and
we create them in R using the c-function, c( ); the ‘c’ stands for collection. This is the exact
analogue of a Set, as described in Module 2. So let’s suppose that we want to calculate the BMI
for 3 people. Let’s define a vector, we can call it wt again, and type
wt = c <left parenthesis> 69.2 <comma> 54.6 <comma> 68.9 <right parenthesis>
Figure: Defining a vector of body-weight values using the collection function c().
Because we’ve defined this as a variable, R has suppressed the output. But to see what this
looks like, we can just call the variable at the command prompt.
Figure: Verifying contents of a vector variable at the command prompt.
Note also that we have “over-written” the variable wt, changing its value. This is totally
legitimate practice in R, and happens all the time in real coding.
We can now define a second vector, call it ht,
ht = c <left parenthesis> 172.3 <comma> 164.8 <comma> 176.6 <right parenthesis>
Figure: Defining a vector of heights
Now that we have a vector of body weights and a vector of heights, we can calculate BMI for all
three individuals. Let’s execute the calculation, but store the result as a new variable, call it
bmi:
Figure: Calculating BMI for multiple individuals at the same time using vectors
Just like the other variables we’ve seen, R will not show the values unless specifically
commanded to. But we want to see the BMI values, so let’s call for this:
Figure: Accessing the calculated BMI values; result is itself a vector.
Excellent! Three BMI values stored in a vector variable! And if we cross-check these against the
NHANES_sample, we confirm: we get the same values.
The important thing to note here is that R treated our variables, wt and ht, just like any other
numerical quantity. This is a powerful advantage that coding allows us to leverage: we can use
two existing variables (here: height and weight) and synthesize a new variable (BMI)
symbolically, using a formula that might be found in, say, a text book; with the result being an
actual numerical result describes a real person.
Concept 5: Functions
Vector variables are just the first way that R makes life easy. The second way is through
functions. In programming, function has a special definition: it’s a set of procedures operating
on a variable. You’ve already seen a function: the c() function collects a set of numbers into a
vector. Let’s introduce another simple function: the sum.
Recall from earlier in this conversation, we saw that if we had two baby boys each
weighing 7.9 kg, and two baby girls each weight 7.3 kg, the total combined weight is 30.4 kg.
Let’s see how we might construct this calculation using the sum function:
Figure: Calculating the sum over four baby body-weight values using the sum function
Just that easy!
First, define a vector, b, for Baby Body-weights, and operate the sum function on it. In this
scenario, we call b the “argument” for the function. This is a subtle but valuable distinction
between the BMI calculation and the summed body weight calculation: in the BMI example, we
performed our own arithmetical operations using the basic operators * / and ^; in this sum
calculation, we used a pre-packaged function in R to calculate the sum for us. R’s functions
allow arithmetic to be performed accurately and quickly on a large vector with just a few
keystrokes.
Concept 6: Plotting
Plotting in R is simple and satisfying!
In the previous module we discussed a linear approximation function that related body weight
to height
Weight = 6 pounds per inch <times> height in inches <minus> 250 pounds,
Phrased as a numerical function:
w = 6*h - 250
When plotting this function by hand, we created three test-points, evaluated the function, and
plotted the x- and f(x) values on the Cartesian Plane. Plotting in R is similar. Let’s create the
same three test points, this time as a vector:
x = c(60,65,70)
FIGURE: Defining the independent values as vector h (height).
And we’ll map these independent values onto their proper dependent values by implementing
the operations of the function; we’ll assign this to a variable ‘y’:
Figure: Calculating dependent variable for a plot by coding the function
…R suppresses the output when making an assignment, so in order to verify that you’ve
calculated the y-values correctly, just type the variable name into the command prompt and hit
<ENTER>; R will display the values
Figure: Visually verifying vector contents at the command line
Plotting is just a simple command plot(), with two arguments. Remember, arguments are
what’s written inside the parentheses of a function.
Figure: Plotting a series of points via plot().
The result is a plot of three points, shown as open-circles, which is R’s default plot style. Notice
that R provides critical chart elements automatically: axis, axis ticks, labels.
170
160
150
140
y
130
120
110
60 62 64 66 68 70
Figure: Graphical element generated following plot of two vectors.
In Module 2, we also showed drawing a line to connect the dots. This can be added to a chart in
R with a simple addition of another command, lines().
Figure: Adding a line to the extant plot via lines().
Note that these two functions, plot() and lines(), have the same arguments, but serve
different purposes.
Our result is a plot that draws a straight line between the points.
170
160
150
140
y
130
120
110
60 62 64 66 68 70
Figure: Adding a line to connect the points in our plot of weight versus height.
Outro
Wonderful! Hopefully this Module has shown you that it doesn’t take much to do some
awesome things in R.
In this module we learned how to open and navigate the R user interface, perform basic
arithmetic using R as a calculator, create and manipulate variables including vectors, and how
to operate on variables using R’s built-in functions. Lastly, we created plots using R.
It is so exciting be started on our R journey!
For a practice problem set and skills check, head on over to the course website and complete
the rest of the Module materials!