Calculus

  • derivation
dx <- deriv(y ~ x^3, "x"); dx
## expression({
##     .value <- x^3
##     .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
##     .grad[, "x"] <- 3 * x^2
##     attr(.value, "gradient") <- .grad
##     .value
## })
mode(dx)
## [1] "expression"
x<-1:2   
eval(dx)
## [1] 1 8
## attr(,"gradient")
##       x
## [1,]  3
## [2,] 12
dx <- deriv(y ~ sin(x), "x", func= TRUE) ;  
mode(dx)
## [1] "function"
dx(c(pi,4*pi))  
## [1]  1.224606e-16 -4.898425e-16
## attr(,"gradient")
##       x
## [1,] -1
## [2,]  1
a<-2                
dx<-deriv(y~a*cos(a*x),"x",func = TRUE)    
dx(pi/3)
## [1] -1
## attr(,"gradient")
##              x
## [1,] -3.464102
fxy = expression(2*x^2+y+3*x*y^2)
dxy = deriv(fxy, c("x", "y"), func = TRUE)
dxy(1,2)  
## [1] 16
## attr(,"gradient")
##       x  y
## [1,] 16 13
  • integration
integrate(dnorm, -1.96, 1.96)
## 0.9500042 with absolute error < 1e-11
integrate(dnorm, -Inf, Inf)
## 1 with absolute error < 9.4e-05
integrand <- function(x) {1/((x+1)*sqrt(x))}
 
integrate(integrand, lower = 0, upper = Inf)
## 3.141593 with absolute error < 2.7e-05
 integrand <- function(x) {sin(x)}
 integrate(integrand, lower = 0, upper = pi/2) 
## 1 with absolute error < 1.1e-14
  • create random variables with specific distributions
 dnorm(0)# density at a number 
## [1] 0.3989423
 pnorm(1.28)# cumulative possibility 
## [1] 0.8997274
 qnorm(0.95)#  quantile
## [1] 1.644854
 rnorm(10)# random numbers
##  [1]  0.1018395  0.5766540  0.2044187  0.1288622 -0.9548175  0.3160764
##  [7]  0.8296003  0.9179508 -1.0023496 -0.5275846

using covariance matrix to generate Gaussian multiple variables

 library(MASS)
 Sigma <- matrix(c(10,3,3,2),2,2)
 mvrnorm(n=20, rep(0, 2), Sigma)
##             [,1]         [,2]
##  [1,]  0.7725512  0.005199494
##  [2,] -4.9335658 -1.883786811
##  [3,]  3.3987614  0.576107559
##  [4,] -0.7874838 -0.505896692
##  [5,] -0.1228839  0.854528861
##  [6,]  1.4781497  1.505112202
##  [7,] -2.8267925 -1.075966186
##  [8,] -3.5580101 -0.591663438
##  [9,] -2.0013537 -0.871950931
## [10,]  1.4059231  0.607912012
## [11,]  5.0534385  2.770152934
## [12,]  1.8848228  2.204973968
## [13,]  1.8880242  0.560264997
## [14,] -2.0926514 -1.822969570
## [15,]  0.4036719 -0.915990167
## [16,] -2.5335928 -1.336582825
## [17,] -3.3074977 -0.130202480
## [18,]  3.0005205  0.999036907
## [19,] -2.4534603 -2.364769769
## [20,] -7.7121698 -1.283683328