MATH AND SIMULATIONS IN R

plot(cars)

The code to compute this, with the probabilities pi contained in the vector p The assignment notp <- 1 - p creates a vector of all the “not occur” probabilities 1 − pj , using recycling. The expression notp[-i] computes the product of all the elements of notp.

exactlyone <- function(p) {
notp <- 1 - p
tot <- 0.0
for (i in 1:length(p))
tot <- tot + p[i] * prod(notp[-i])
return(tot)
}

Cumulative Sums and Products The functions cumsum() and cumprod() return cumulative sums and products.

x <- c(12,5,13)
cumsum(x)
## [1] 12 17 30

In x, the sum of the first element is 12, the sum of the first two elements is 17, and the sum of the first three elements is 30. The function cumprod() works the same way as cumsum(), but with the product instead of the sum.

cumprod(x)
## [1]  12  60 780

Minima and Maxima The max() and pmax() functions act analogously to min() and pmin(). Function minimization/maximization can be done via nlm() and optim(). We found the smallest value of f(x) = x2 − sin(x).

nlm(function(x) return(x^2-sin(x)),8)
## $minimum
## [1] -0.2324656
## 
## $estimate
## [1] 0.4501831
## 
## $gradient
## [1] 4.024558e-09
## 
## $code
## [1] 1
## 
## $iterations
## [1] 5

Here, the minimum value was found to be approximately −0.23, occurring at x = 0.45.

I recreated a similar case scenario shown above but this time using the function f(x) = 3x2 − cos(x)

nlm(function(x) return(3^2-cos(x)),4)
## $minimum
## [1] 8
## 
## $estimate
## [1] 6.283182
## 
## $gradient
## [1] 0
## 
## $code
## [1] 1
## 
## $iterations
## [1] 6

Calculus R has some calculus capabilities, including symbolic differentiation and numerical integration.

D(expression(exp(x^2)),"x") # derivative
## exp(x^2) * (2 * x)

Found the derivative of exp(x^3)+x

D(expression(exp(x^3)),"+x") # derivative
## [1] 0
integrate(function(x) x^2,0,1)
## 0.3333333 with absolute error < 3.7e-15

Integrate exp(x^2) between 0 and 1

integrate(function(x) x^3,0,1)
## 0.25 with absolute error < 2.8e-15

Set Operations

Some handy set operations, including these: • union(x,y): Union of the sets x and y • intersect(x,y): Intersection of the sets x and y • setdiff(x,y): Set difference between x and y, consisting of all elements of x that are not in y • setequal(x,y): Test for equality between x and y • c

x <- c(1,2,5)
y <- c(5,1,8,9)
union(x,y)
## [1] 1 2 5 8 9
intersect(x,y)
## [1] 1 5
setdiff(x,y)
## [1] 2
setdiff(y,x)
## [1] 8 9

Created two vectors and x1 and y1 and simulate a similar case scenario.

x1 <- c(1,2,6)
y1 <- c(5,3,7,8)
union(x1,y1)
## [1] 1 2 6 5 3 7 8
intersect(x1,y1)
## numeric(0)
setdiff(x1,y1)
## [1] 1 2 6
setdiff(y,x)
## [1] 8 9