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;

[1] 4

The notation [1] 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)

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

Log using base 10

> log10(10)

[1] 1

Exponentiation

> exp(2)

[1] 7.389056

Square Root

> sqrt(4)

[1] 2

Absolute Value

> abs(-4)

[1] 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:

yes   6 × (5 + 3) = 6 × 8 =

48

 
no   6 × (5 + 3) = 30 + 3 =

33

(wrong)

Exponents (Powers, Roots) before Multiply, Divide, Add or Subtract.

yes   5 × 22 = 5 × 4 =

20

 
no   5 × 22 = 102 =

100

(wrong)

 

Multiply or Divide before you Add or Subtract.

yes   2 + 5 × 3 = 2 + 15 =

17

 
no   2 + 5 × 3 = 7 × 3 =

21

(wrong)

Otherwise just go left to right.

yes   30 ÷ 5 × 3 = 6 × 3 =

18

 
no   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]

 

alternative accessible content