Chief among R’s many capabilities are basic mathematical operations, making it a severely overdesigned calculator. The only thing a TI-84 has on R is that you can’t play Super Mario Brothers with the latter - yet (package developers… if your listening…).
So what?
Arithmetic operations in R are key to transforming your data, whether calculating property code violations per capita or converting U.S. dollars to Indian rupees. In short, you use them to make new variables from existing ones. When we combine arithmetic with objects that store one or more values, we’re dangerously close to practicing algebra.
In this chapter, we’ll learn and practice basic arithmetic functions in R, assign calculations and their resulting values to objects, and use those objects in algebraic operations. Key concepts include:
Everything you need to know in a few bullet points:
+
, -
, *
, /
, ^
, ( )
x
stores the value 3
after calling x <- 3
x + 2
equals 5
"What sort of free will is left when we come to tabulation and arithmetic? When it will all be a case of twice two makes four?
You don’t need free will to determine that twice two is four." (Dostoyevsky)
You remember arithmetic, right? That peculiar field of mathematics in which people who admittedly “don’t math”, for whatever reason, actually use every day?
Arithmetic operators in R work just like they did in primary school, including addition, subtraction, multiplication, division, and exponentiation:
+
or addition, e.g. 2 + 2
-
or subtraction, e.g. 2 - 2
*
or multiplication, e.g. 2 * 2
/
or division, e.g. 2 / 2
^
or exponentiation, e.g. 2 ^ 2
( )
for order of operations, e.g. ((2 + 2) * 2)
The following example has a number of operations. Run the code to see what happens:
Eureka! Forget your mobile phone’s calculator app. Install R on it!
(Plus, you can browse Reddit during class, but it looks like you’re working).
Instructions: Perform the following arithmetic operation in R.
Tip: Numeric values in R don’t use commas.
Here’s another blast from the past: the operator precedence. At least, that’s what it’s called in programming languages. You probably remember it as the order of operations.
If you don’t recall the specific rules, perhaps you remember the mnemonic devices: PEMDAS or Please Excuse My Dear Aunt Sally. We are not sure know what Aunt Sally did, but we are pretty sure she deserves whatever punshinment she received.
PEMDAS reminds us the order arithmetic operations are evaluated, a.k.a. the order of operations:
( )
^
*
/
+
-
Arithmetic operations in R are also evaluated in the same order. Can you guess the results before evaluating the expressions? Press “Run” to execute the code and see the results:
Note that R is indifferent to order of operations for addition vs subtraction, and multiplication vs division.
For cases where both occur the code is just executed from left to right.
Instructions:
The formula to calculate a monthly mortgage payment based upon the loan amount, annual interest rate, and loan term (in months) is calculated as follows:
\[ PAYMENT = \frac{principal \cdot \frac{interest \ rate}{12}}{1-(1+\frac{interest \ rate}{12})^{- \ months}} \]
Let’s say we have a $100,000 loan at a 5% interest rate amortized over 360 months (30 years). The payments would be as follows:
\[ PAYMENT = \frac{ 100k \cdot \frac{0.05}{12}}{1-(1+\frac{0.05}{12})^{- \ 360}} \]
Can you type the formula into R correctly? The payment should come to $536.82 a month.
"The philosophical workers… have to fix and formalize some great existing body of valuations - that is to say…
…creations of value, which have become prevalent, and are for a time called ‘truths’…" (Nietzsche)
Objects are the meat and potatoes of R. They store information like datasets, function code, individual values, and even metadata, e.g. coefficents in linear models.
But how do we create an object?
We use assignment to create an object and store data in it. This requires the assignment operator, or the <-
arrow.
Assignment can be used to store external data that was imported into R, to save a statistic that we calculated, or remember data we type into R ourselves.
Assign the values 3 and 4 to objects x
and y
, respectively. Note that typing an object’s name will report the object values.
Like algebra, x
and y
are used to represent numeric values.
Unlike algebra, we can store many values in objects, including other objects!
What do you think the following will return?
Why does R use the <-
for assignment?
Technically R allows you to use the equals =
operator for assignment instead of using the arrow <-
.
BUT YOU SHOULD NEVER DO IT!.
Assignment is important enough that the arrow helps keep your code easy to read.
Also, mind your spaces!
What will the following statements return?
When creating new objects there are both rules and conventions for naming them.
The rules are fairly simple:
b
and B
are different objects.x.01 <- 99 # good
x_01 <- 99 # this works
01.x <- 99 # produces an error
.x <- 99 # this works
.1x <- 99 # this doesn't
_x <- 99 # oddly this doesn't
In general it is good to name objects so they are easy to remember. You can combine words using one of three conventions:
Some people have strong views on these. You should find something that works for you and be consistent.
The following resources are helpful in learning more about arithmetic operators in R:
The Hangover (2009) The Hunger Games (2010)