1 R: An Overdesigned Calculator



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



1.1 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

1.1 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





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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiI3ICsgMyAgICAgICAjIEFkZGl0aW9uXG5cbjggLSAxMiAgICAgICMgU3VidHJhY3Rpb25cblxuOSAqIDkgICAgICAgIyBNdWx0aXBsaWNhdGlvblxuXG4xMCAvIDMgICAgICAjIERpdmlzaW9uXG5cbjEwIF4gMyAgICAgICMgRXhwb25lbnRpYXRpb24ifQ==


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


1.2.1 Your Turn

Instructions: Perform the following arithmetic operation in R.

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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFJhaXNlIDUgdG8gdGhlIGZpZnRoIHBvd2VyXG5cbiMgU3VidHJhY3QgMzAgZnJvbSAxMDBcblxuIyBEaXZpZGUgMSwwMDAgYnkgMzAwIn0=


*Arithmetic operators are the most atomic functions in R programming.*

Arithmetic operators are the most atomic functions in R programming.

Source: XKCD



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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIGVhc3kgb25lXG41ICsgMTAgLyA1ICAgIFxuXG4jIGhhcmRlclxuNSAtIDEwICsgNSBcbjUgKyAxMCAtIDUgIFxuXG4jIHNpbWlsYXJseVxuNSAqIDEwIC8gNSAgIFxuNSAvIDEwICogNSBcblxuIyBlYXNpZXJcbjMgKiAyIF4gMlxuXG4jIGhtbW1cbjIgKiAoMiArIDMpICogM1xuXG4jIGh1aD9cbiggMiArIDMgKSAvIDUgKiAyXG4oIDIgKyAzICkgKiA1IC8gMlxuKCAyICsgMyApIC8gMiAqIDUifQ==


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.

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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFR5cGUgeW91ciBmb3JtdWxhIGhlcmUifQ==


*A different programming language, but you get the gist.*

A different programming language, but you get the gist.

Source: Prairie World Comics



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


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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiJ4IDwtIDMgICAgICAgICMgQXNzaWduIDIwIHRvIFwieFwiXG5cbnkgPC0gNCAgICAgICAgIyBBc3NpZ24gNDgwIHRvIFwieVwiXG5cbnggICAgICAgICAgICAgIyBXaWxsIHRoaXMgcHJpbnQgXCJ4XCIgb3IgMyA/XG5cbnggKiB5ICAgICAgICAgIn0=


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

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

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiJ4IDwtIDIwICAgICAgIyBBc3NpZ24gMjAgdG8gXCJ4XCJcblxueSA8LSA0MCAgICAgICMgQXNzaWduIDQwIHRvIFwieVwiXG5cbnogPC0geCArIHkgICAjIEFzc2lnbiB0aGUgc3VtIG9mIFwieFwiIGFuZCBcInlcIiB0byBcInpcIlxuXG56ICAgICAgICAgICAgIyBQcmludCB6In0=


What do you think the following will return?

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiJ4IDwtIDIwICAgICAgXG55IDwtIHggICAgXG54IDwtIDMwICBcblxueSAgICMgcHJpbnQgdGhlIHZhbHVlIHN0b3JlZCBieSB5In0=


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



2.0.1 Your Turn

What will the following statements return?

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiJ4IDwtIDVcbnggPC0gMTBcbnhcblxueCA8LSA1XG54IDwgLSAxMCAgXG54XG5cbjUgPC0geFxuNVxuXG41IC0+IHggICAgXG54ICBcblxueCA9IDVcbnhcblxuNSA9IHggICAgXG54IFxuXG55IDwtIDEwXG54IDwtIHkgPC0gM1xueCJ9

Jennifer Lawrence practicing assignment.


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

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

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


*You can't do this anymore, sadly.*

You can’t do this anymore, sadly.

Source: XKCD



2.2 Further Resources

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



2.3 Works Cited

The Hangover (2009) The Hunger Games (2010)