2 min read

Elementary Mathematics using R

The basics

This is a compilation of basic codes for doing elementary mathematics (college algebra, calculus)

The best software for doing mathematics may be Mathematica, Maple, MatLab, Sage and other software. However, you can also do some math using R with the convenience of RStudio and R Markdown.

# install.packages("mosaic", "mosaicCalc", "calculus")
## Required libraries
library(mosaic)
library(mosaicCalc)
library(calculus)
library("ggplot2")

## Given g(x)=3*x^2 -2*x +1, find g(2)  ##base R, that is,no extra package is used.
g <- function(x){3*x^2 -2*x +1}
g(2)
## [1] 9

## Given g(x)=3*x^2 -2*x +1, find g(2)  ##mosaic
g<-makeFun(3*x^2 -2*x +1 ~ x)
g(2)
## [1] 9

##Plot the function y=3x^2-x-2 on the interval [-10, 10]  ## base R
curve(3*x^2 -2*x +1, -10, 10)


## Plot the function y=3x^2-x-2 on the interval [-10, 10]  ##moasaic
plotFun(3*x^2 -2*x +1 ~x, x.lim=range(-10,10) )


## Plot the function y=3x^2-x-2 on the interval [-10, 10].  ##ggplot2
eq = function(x){3*x^2 -2*x +1}
g<-ggplot(data.frame(x=c(-10, 10)), aes(x=x))
g<-g+ stat_function(fun=eq)
g


## Solve the equation x^2 +x -6=0 for x.
findZeros(x^2 +x -6 ~ x, x.lim=range(-Inf, Inf))
##    x
## 1 -3
## 2  2

## Solve a system of linear equatiioms
##   solve the system:  2x + 3y = 5 
##                      5x - y = 7   for x and y. 

A<-matrix(c(2,3,5,-1), nrow=2, ncol=2, byrow=TRUE) ## see ?matrix
b<-matrix(c(5,7), nrow=2, ncol=1, byrow=TRUE)
solve(A,b)
## Find the derivative of the function f(x)= 2x^3+3x^2 +2x -5sin^2(x) +ln(x)      ##mosaicCal

D(2*x^3 + 3*x^2 +2*x - 5*sin(x)^2 + log(x) ~ x)
## function (x) 
## 2 * (3 * x^2) + 3 * (2 * x) + 2 - 5 * (2 * (cos(x) * sin(x))) + 
##     1/x
## Find the derivative of the function f(x)= 2x^3+3x^2 +2x -5sin^2(x) +ln(x)      ## "calculus" package
derivative(f = "2*x^3 + 3*x^2 +2*x - 5*sin(x)^2 + log(x)", var = "x")
##                                          [,1]                                                                 
## 2*x^3 + 3*x^2 +2*x - 5*sin(x)^2 + log(x) "2 * (3 * x^2) + 3 * (2 * x) + 2 - 5 * (2 * (cos(x) * sin(x))) + 1/x"

## Given F(x)= 3*x^2 - 2*x +1, find F'(2)  (derivative of F at x=2)  ##calculus
derivative(f = "3*x^2 - 2*x +1", var = c("x" = 2))
##      [,1]
## [1,]   10

## Given F(x)= 3*x^2 - 2*x +1, find F'(2)  (derivative of F at x=2)  ##mosaicCal
g<- D(3*x^2 -2*x + 1 ~ x)
g(2)
## [1] 10

## Evaluate the definite integral \int_{-1}^{2}(x^2-2x+1)dx       ##mosaicCal
F<-antiD(x^2-2*x+1 ~ x)
F(2)-F(-1)
## [1] 3

(DRAFT=TRUE; will be updated)