# Load libraries for use
library(mosaic) # For function making
library(mosaicCalc) # For Calculus
library(ggplot2) # For graph plottingUsing R to Write Functions and Models for Agricultural and Economic Research: Suitability, Potential and Constraints for Undergraduate Students
Scientific Day: In Celebration of the 1st Anniversary of Confucius Institute of RUA
Hin Lyhour (Ph.D.)
Senoir lecturer and researcher
Faculty of Agricultural Biosystems Engineering
Royal University of Agriculture, Cambodia
hlyhour@rua.edu.kh
Date: June 27, 2025
1. Introduction
R can be used to create functions quickly and effectively and plot graphs based on any formulas we want to use. After creating the formulas, we can do quick calculation, do derivatives, and integration.
To download the R Program and RStudio, please type https://posit.co/download/rstudio-desktop/.
However, before being able to use R codes, basic learning is required (about 2-4 hours of intensive learning).
For more information or interest in my research, please visit:
- my ORCiD at https://orcid.org/0000-0001-5180-3450 or
- my google scholar account at https://scholar.google.com/citations?user=RRtLBl4AAAAJ&hl=en.
Before they can be used, prior installations are needed, but only one time. The installation can be done, for example, by typing
install.packages("mosaic").
Note: Libraries are loaded any time an R project is opened for execution.
2. Create Function with one variable
# Create an equation (quadratic equation)
f <- makeFun(2*x^2 - 8*x + 7~x)To create a function, we need a function name
f, and the name can be whatever we like. It is just used for subsequent tasks.Then, use type
<-, or=: they are the same. Afterwards, we typemakeFunand(). In the brackets, we can write any formula we want to use. Remember: please use mathematical signs+, -, /, or *similar to MS Excel.Then, we need to type
~and the variable, for example,xlike the function above. In fact, we can use any letters we like, but they must be consistent.
# Show the equation result
ffunction (x)
2 * x^2 - 8 * x + 7
3. Find zeros
## Find zero
findZeros(f(x)~x) x
1 1.2929
2 2.7071
To find zero is to find x with which, the function is equal to zero. We just write findZero and (), and in the brackets, we write the formula we have created before, followed by ~ and x.
4. Derivative
## Do the derivative.
f1 <- D(f(x)~x)To do the derivative, we just write D and (), and in the brackets, we write the formula we have created before, followed by ~ and x.
## Show the result of the derivative
f1function (x)
4 * (x - 2)
5. Integration
## Integration
ff <- antiD(f(x)~x)To do the integration, we just write antiD and (), and in the brackets, we write the formula we have created before f(x), followed by ~ and x.
## Show the result of the integration
fffunction (x, C = 0)
(2 * x^3 - 12 * x^2 + 21 * x)/3 + C
6. Plot graphs
6.1 Plot a signal graph
ggplot() +
geom_function(fun=f, color="red")+
xlim(-10, 10)To plot the graph, we just write ggplot(), +, and geom_fuction(). In the brackets, we write the formula we want to use to make a graph f(x), and if we need a specific color, we add , color="red". To specify the range of x, we type xlim(-10,10), depending on the range we want.
6.1 Plot multiple lines on the sampe graphs
ggplot() +
geom_function(fun=f, color="red")+
geom_function(fun=f1, color="blue")+
geom_function(fun=ff, color="green")+
xlim(-10, 10)+
geom_text(aes(x=1, y=50),
label="y1", color="red")+
geom_text(aes(x=5, y=0),
label="y2", color="blue")To plot multiple lines, the process is the same. The reader can follow the codes shown above.
7. Caculation of the function
## Calcuate f when x = 3
f(3)[1] 1
## Calcuate f when x = 3 & 5
f(c(3, 5))[1] 1 17
## Calcuate f when x = 1:10
f(1:10) [1] 1 -1 1 7 17 31 49 71 97 127
To caculate the function, we just write any functions we have created before, then type the number in the brackets.
8. Function with two or more variables
z <- makeFun(x^2 + y^2 + 3*x*y - 5~x&y)
## Show the result
zfunction (x, y)
x^2 + y^2 + 3 * x * y - 5
To create a function with two more variables, the process is the same. We type makeFun and (). In the brackets, we can write any formula we want to use. Remember: please use mathematical signs +, -, /, or * similar to MS Excel. Then, we need to type ~ and the variables, for example, x&y if we have two variables. In fact, we can use any letters we like, but they must be consistent.
8.1 Caculation
## Calculate z when x= 4, y = 3
z(4, 3)[1] 56
8.2 Derivative
## Derivative
z1 <- D(z(x,y)~x)## show z1
z1function (x, y)
2 * x + 3 * y
9. Create Cobb-douglas fuction
## Create an equation for Cobb-douglas
output <- makeFun(A*L^alpha*K^beta~L&K,
A = 1, alpha = 0.6, beta = 0.4)## Show the equation
outputfunction (L, K, A = 1, alpha = 0.6, beta = 0.4)
A * L^alpha * K^beta
If we look at the formula created above, the process of making it is similar. However, it is just an example of creating a real formula that we know. We can create any formula we want using the same procedure taught in this lesson.
# Calculate douglass when L = 100 & K = 50
output(100, 50)[1] 75.78583
10. Surface plot
plotFun(output(L,K)~L&K, L.lim=c(1, 100), K.lim=c(1,50))11. 3D graph
surface_plot(L^0.6*K^0.4~L&K,
bounds(L=1:6, K=1:10))The 3D graph is rotatable. We just click the graph and move it to any position we think fit.
Additional readings
- https://cran.r-project.org/web/packages/mosaicCalc/vignettes/Calculus_with_R.html
- https://webwork.collegeofidaho.edu/MAT150Resources/StartR-August-2012.pdf
- https://digitalcommons.unl.edu/cgi/viewcontent.cgi?article=1577&context=r-journal
- https://github.com/mlaviolet/Mosaic-cheatsheets/blob/master/mosaic-cheatsheet-gf.pdf
- https://rstudio.github.io/cheatsheets/quarto.pdf
- https://posit.co/wp-content/uploads/2022/10/data-visualization-1.pdf
Thank you. If you want to learning specific topics, please give comments.