7  R: An Overdesigned Calculator


7.1 Introduction

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.



7.2 Key Concepts

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:

  • Arithmetic Operators
  • Operator Precedence
  • Assignment

7.3 Key Takeaways

Everything you need to know in a few bullet points:

  • Arithmetic operators include: +, -, *, /, ^, ( )
  • Calculations follow the order of operations
  • Create objects with assignment:
    • x stores the value 3 after calling x <- 3
  • Numeric bjects act like variables in algebra:
    • x + 2 equals 5





7.4 Arithmetic Operators

“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:

7 + 3       # Addition

8 - 12      # Subtraction

9 * 9       # Multiplication

10 / 3      # Division

10 ^ 3      # Exponentiation


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).


7.4.1 Your Turn

Instructions: Perform the following arithmetic operation in R.

Tip: Numeric values in R don’t use commas.

# Raise 5 to the fifth power

# Subtract 30 from 100

# Divide 1,000 by 300


Arithmetic operators are the most atomic functions in R programming.
Source: XKCD



7.5 Order of Operations

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:

  1. Parenthesis, or expressions inside ( )
  2. Exponents, or raising one value to the power of another with ^
  3. Multiplication, or multiplying values with *
  4. Division, or dividing values with /
  5. Addition, or adding values with +
  6. Subtraction, or subtracting values with -

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:

# easy one
5 + 10 / 5    

# harder
5 - 10 + 5 
5 + 10 - 5  

# similarly
5 * 10 / 5   
5 / 10 * 5 

# easier
3 * 2 ^ 2

# hmmm
2 * (2 + 3) * 3

# huh?
( 2 + 3 ) / 5 * 2
( 2 + 3 ) * 5 / 2
( 2 + 3 ) / 2 * 5


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.

7.5.1 Your Turn

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.

# Type your formula here



8 Assignment

“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.

x <- read.csv( "FileName.csv" ) 

x <- mean( y )

x <- c("Adam","Susie","Tony")


Assign the values 3 and 4 to objects x and y, respectively. Note that typing an object’s name will report the object values.

x <- 3        # Assign 20 to "x"

y <- 4        # Assign 480 to "y"

x             # Will this print "x" or 3 ?

x * y         


Like algebra, x and y are used to represent numeric values.

Unlike algebra, we can store many values in objects, including other objects!

x <- 20      # Assign 20 to "x"

y <- 40      # Assign 40 to "y"

z <- x + y   # Assign the sum of "x" and "y" to "z"

z            # Print z


What do you think the following will return?

x <- 20      
y <- x    
x <- 30  

y   # print the value stored by y


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!

  • x <- y is assignment
  • x < - y is less than negative y



8.0.1 Your Turn

What will the following statements return?

x <- 5
x <- 10
x

x <- 5
x < - 10  
x

5 <- x
5

5 -> x    
x  

x = 5
x

5 = x    
x 

y <- 10
x <- y <- 3
x


8.1 Valid Object Names

When creating new objects there are both rules and conventions for naming them.

The rules are fairly simple:

  1. R is case sensitive, so b and B are different objects.
  2. Object names can include letters, periods and underscores.
  3. Object names can include numbers, but cannot begin with a number.
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:

  • Camel Caps
  • Underscores
  • Periods
myData  <- 99  # camel caps
my_data <- 99  # underscore
my.data <- 99  # dot case

Some people have strong views on these. You should find something that works for you and be consistent.



8.2 Further Resources

The following resources are helpful in learning more about arithmetic operators in R:



8.3 Works Cited

The Hangover (2009) The Hunger Games (2010)