Monday, June 15, 2015

Numeric Operators in R

Numeric Operators in R

Part of Mike's Big Data, Data Mining, and Analytics Tutorial  



R provides a number of operators for performing mathematical operations on numbers and vectors. Unlike most other programming languages, R can seamlessly take objects of different forms (single numbers, vectors, arrays) and perform operations with them.
In the case when two inputs have different lengths, R will “recycle” elements from the shorter input by repeating the shorter input to get the correct length. This is best demonstrated by example:
a<-rep(1,10) # 1 1 1 1 1 1 1 1 1 1 
b<-1:3       # 1 2 3
#b treated as# 1 2 3 1 2 3 1 2 3 1
#Note the warning...
a+b          # 2 3 4 2 3 4 2 3 4 2
## Warning in a + b: longer object length is not a multiple of shorter object
## length
##  [1] 2 3 4 2 3 4 2 3 4 2
In general, I think recycling elements makes understanding R code harder, and I would generally treat it as an antipattern in R (i.e. don’t do it…). In addition to making code harder to understand, it will also help you start a bad habit of ignoring errors and warnings in R. There are better methods (rep,expand.grid,combn, etc) that preserve code readability if you (or someone else) needs to do any review/modification in the future.
Like most other programming languages, R operators follow a precedence that is similar to the precidence taught to math students (i.e. parentheses first, then multiply/divide, then addition/subtraction). I will cover this section discussing the most common operators and precedence from high to low (see ?Syntax for the full list).

^ Exponentiation

An exponent can be defined as one number (the base) multiplied by itself a number of times (the exponent). Here 4 is the exponent and 2 is the base:
\[ 2^4 = 2 \cdot 2 \cdot 2 \cdot 2 = 16 \]
In the case of a non-whole exponent, exponentiation works as an nth root operation. For example:
\[ 8^{\bar{.3}} = 8^{\frac{1}{3}} = \sqrt[3]{8^1} = \sqrt[3]{8} = 2 \]
Negative exponents work as division operations. For example:
\[ 2^{-3} = \frac{1}{2^3} = \frac {1}{8} = 0.125 \]
R accomplishes exponentiation via the ^ operator. A few examples:
2^3#Exponent of a single number
## [1] 8
(1:10)^2#Exponent over an entire vector
##  [1]   1   4   9  16  25  36  49  64  81 100
c(4,9,16,25,36)^(1/2)#nth root operation
## [1] 2 3 4 5 6

* Multiplication and / Division Operators

Multiplication can be defined as the repeated addition of a number. Example:
\[ 5 * 3 = 5 + 5 + 5 = 15 \]
Division can be defined in terms of splitting a quantity (called the numerator) between a set of groups (denominator). Example: 20 split between 5 groups yields 4 for each of the 5 groups:
\[ 20 / 5 = 4 \]
Various rules exist and are taught in low level mathematics courses for finding multiplication and subtraction for non-whole numbers by hand.
R accomplishes multiplication with the * operator. A few examples:
2*2                    #Multiplication of two numbers
## [1] 4
(1:5)*rep(2,5)         #Multiplication of vectors
## [1]  2  4  6  8 10
c(1,2,3,4,5)*c(2,2,2,2,2) #Same as above
## [1]  2  4  6  8 10
(1:5)*2                #Multiplication of a vector by a number (all elements multiplied)
## [1]  2  4  6  8 10
The vector example above illustrated (O are input, X are output):

R accomplishes division with the / operator. A few examples:
4/2                    #Division of two numbers
## [1] 2
seq(2,10,by=2)/rep(2,5)#Division of vectors
## [1] 1 2 3 4 5
c(2,4,6,8,10)/c(2,2,2,2,2) #Same as above
## [1] 1 2 3 4 5
seq(2,10,by=2)/2       #Division of a vector by a number (all elements divided by number)
## [1] 1 2 3 4 5
The vector example above illustrated (O are input, X are output):

The input objects need to be numeric to utilize numeric operators. An example is that lists can’t be multiplied/divided directly:
list(x=2,y=3) * list(y=2,x=3) #Might yield list(x=6,y=6)? Nope...
## Error in list(x = 2, y = 3) * list(y = 2, x = 3): non-numeric argument to binary operator
Matrix multiplication uses a different operator (%*%). See the post on Matrix operations for more details.

+ Addition and - Subtraction Operators

Addition can be thought of as finding the magnitude of two combined quantities.
\[ 1 + 1 = 2 \]
Subtraction can generally be thought of as finding the difference between two values.
\[ 2 - 1 = 1 \]
R accomplishes addition with the + operator. A few examples:
+5        #Unary addition operator - no change/effect
## [1] 5
2+10      #Addition of 2 numbers
## [1] 12
1:10+2    #Addition of number and vector
##  [1]  3  4  5  6  7  8  9 10 11 12
1:10+11:20#Addition of 2 vectors
##  [1] 12 14 16 18 20 22 24 26 28 30
The vector example above illustrated (O are input, X are output):

R accomplishes subtraction with the - operator. A few examples:
-5        #Unary negation operator - creates a negated quantity
## [1] -5
12-2      #Subtraction of 2 numbers
## [1] 10
3:12-2    #Subtraction of number and vector
##  [1]  1  2  3  4  5  6  7  8  9 10
11:20-1:10#Subtraction of 2 vectors
##  [1] 10 10 10 10 10 10 10 10 10 10
The vector example above illustrated (O are input, X are output):

R has more operators that will be considered in other posts.
  • Matrix Operations in R
  • Logical Operators in R
  • Bitwise Operators in R

Back to Mike's Big Data, Data Mining, and Analytics Tutorial  


No comments:

Post a Comment