# R as a Calculator

The simplest way to use R is to use it as if it were a calculator. For example, if we want to know what two times two is, you may type

> 2*2;

 4

The notation  indicates that the result is the first element. This is useful later when we have many elements for one variable such as a vector. If you carefully compare this to the previous command, you will notice that we added a semi-colon (;) here. However, the result remains the same since the semicolon is used as the separator for multiple commands. Sometimes, you may want to use built-in functions in your calculations. Here are some examples:

### Natural logs

> log(10)

 2.302585

Note that this is returning the "natural log" of 10, which uses the base "e," which is a constant with an approximate value of 2.71828.

> log10(10)

 1

> exp(2)

 7.389056

> sqrt(4)

 2

### Absolute Value

> abs(-4)

 4 Type in the following commands and describe your observations.   > # case 1 : 1+2 > 2+2; 2*3; 2/5 > # case 2 > 8/2-2*(2-3) > # case 3: > 3*5  * 4   /2

When you observe the results , remember the rules for the order of operations: "PEMDAS."

PEMDAS (From http://www.mathsisfun.com/operation-order-pemdas.html)

## Order of Operations

Do things in Parentheses First. Examples: 6 × (5 + 3) = 6 × 8 = 48 6 × (5 + 3) = 30 + 3 = 33 (wrong)

Exponents (Powers, Roots) before Multiply, Divide, Add or Subtract. 5 × 22 = 5 × 4 = 20 5 × 22 = 102 = 100 (wrong)

Multiply or Divide before you Add or Subtract. 2 + 5 × 3 = 2 + 15 = 17 2 + 5 × 3 = 7 × 3 = 21 (wrong)

Otherwise just go left to right. 30 ÷ 5 × 3 = 6 × 3 = 18 30 ÷ 5 × 3 = 30 ÷ 15 = 2 (wrong)

## How Do I Remember It All ... ? PEMDAS !

 P Parentheses first E Exponents (ie Powers and Square Roots, etc.) MD Multiplication and Division (left-to-right) AS Addition and Subtraction (left-to-right)

The video below provides nice introduction to R, including a review of mathematical operations that can be performed using R as a calculator.

Getting Started With R (R Tutorial 1.1) MarinStatsLectures [Contents ]