R Calculations and Factorials#
We often use R as a scientific calculator. When working in R, we often use the following functions.
Scientific Computing in R#
Basic Arithmetic#
We add, subtract, multiply, divide and indicate powers in the typical way, exactly as on a TI-84 graphing calculator. Suppose we wish to evaluate:
( 3 - 2^3 + 12 / 20 ) * 2
Note that all multiplications must be indicated by an * . R does not understand that a quantity outside the parenthesis indicates multiplication by the quanity inside.
Summations#
If we have vector \(x\), we can sum all of its entries using sum(x). We also have a cool way to sum consecutive integers as in the handshake problem where we needed to evaluate
sum(1:9)
The colon between two numbers creates a vector of consecutive integers from the first number to the second, and we can quickly confirm the famous Gaussian problem:
sum(1:100)
Trigonometry#
The evaluations are simple once we understand the following:
R expects the input angles to be measured in radians.
R understands the keyword pi.
R does not understand the notation \(\sin^2\left(\frac{\pi}{4}\right)\).
sin(pi/4)
sin(pi/4)^2
We have confirmed that the trig functions work normally in R, and that
Factorials, Combinations and Permutations#
Counting problems in probability rely heavily upon combinations and permutations which, in turn, are built upon the factorial.
The Factorial() Function#
factorial(5)
Permutations and Combinations#
Native R includes neither a permutations formula nor a formula for combinations. However, we can easily write formulas for both.
Combinations Formula#
Mathematically, when we say “n choose r,” we mean:
Example: \(\binom{7}{5}\)#
We have the following calculation to evaluate:
Writing a Combinations Function in R#
We have a factorial function in R, so creating a function that evaluates the top line of the equations above is reasonably straightforward:
combin <- function(n, k) {
return(factorial(n) / ( factorial(k)*factorial(n-k) )) }
Testing the function with \(\binom{7}{5}=21\), we see:
combin(7,5)
Permutations#
Notice the following relationship between the two formulas:
Hence, we see that
Writing a Permutations Function in R#
Using the function for combinations, the function for permutations is quite easy to write:
perm <- function(n, k) {
return(combin(n,k) * factorial(k))}
Example: 7 Permute 5#
Algebraically, we calculate:
perm(7,5)
Wrapping Up#
Please note that it will be useful to store these two functions where we can quickly copy-paste them into an R notebook for use doing classwork or homework.
combin <- function(n, k) {
return(factorial(n) / ( factorial(k)*factorial(n-k) )) }
perm <- function(n, k) {
return(combin(n,k) * factorial(k))}