5  Calculator

Author

Jarad Niemi

5.1 Basic calculator operations

All basic calculator operations can be performed in R.

1+2
[1] 3
1-2
[1] -1
1/2
[1] 0.5
1*2
[1] 2
2^3 # same as 2**3
[1] 8

For now, you can ignore the [1] at the beginning of the line, we’ll learn about that when we get to vectors.

5.2 Advanced calculator operations

Many advanced calculator operations are also available.

(1+3)*2 + 100^2  # standard order of operations (PEMDAS)
[1] 10008
sin(2*pi)        # the result is in scientific notation, i.e. -2.449294 x 10^-16 
[1] -2.449294e-16
sqrt(4)
[1] 2
log(10)          # the default is base e
[1] 2.302585
log(10, base = 10)
[1] 1

5.3 Using variables

A real advantage to using R rather than a calculator (or calculator app) is the ability to store quantities using variables.

a = 1
b = 2
a + b
[1] 3
a - b
[1] -1
a / b
[1] 0.5
a * b
[1] 2
b ^ 3
[1] 8

5.3.1 Case sensitive

R is a case sensitive language and therefore you need to be careful about capitalization.

ThisObjectExists <- 3
ThisObjectExists
[1] 3
thisobjectexists # no it doesn't
Error in eval(expr, envir, enclos): object 'thisobjectexists' not found

5.3.2 Valid object names

Valid object names “consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number”.

# Valid object names
a  = 1
.b = 2
# Invalid object names
2a  = 3
.2a = 4
_c  = 5
Error: <text>:2:2: unexpected symbol
1: # Invalid object names
2: 2a
    ^

You cannot use any reserved names as object names, i.e. these names cannot be overwritten.

?Reserved

5.3.3 Tab auto-complete

5.4 Assignment operators =, <-, and ->

When assigning variables values, you can also use arrows <- and -> and you will often see this in code, e.g. 

a <- 1 # recommended
2 -> b # uncommon, but sometimes useful
c = 3  # similar to other languages

Now print them.

a
[1] 1
b
[1] 2
c
[1] 3

5.5 Using informative variable names

While using variables alone is useful, it is much more useful to use informative variables names.

# Rectangle
length <- 4
width  <- 3

area <- length * width
area
[1] 12
perimeter <- 2 * (length + width)



# (Right) Triangle
opposite     <- 1
angleDegrees <- 30
angleRadians <- angleDegrees * pi/180

(adjacent     <- opposite / tan(angleRadians)) # = sqrt(3)
[1] 1.732051
(hypotenuse   <- opposite / sin(angleRadians)) # = 2
[1] 2