x <- 5RStudio Reference Guide for MATH 135
1 Getting Started with RStudio and Quarto
R is a programming language used for mathematics, statistics, and data analysis. RStudio is an interface for working with R.
In this course, we use Quarto Markdown files, which have the extension .qmd. A Quarto document combines R code, mathematical notation, written explanations, and plots in one file.
1.1 Starting a Quarto File
At the beginning of a new document, include the document information and settings provided in the activity instructions. You generally do not need to change these settings. You should, however, replace "Your Name" with your actual name and give your file a reasonable name.
1.2 Loading Packages
Include this code chunk near the beginning of your document. The setup chunk loads the packages needed for the activities.
You only need one setup chunk. The packages must be loaded before you use their functions.
1.3 Saving and Formatting Your Activity
Before submitting your activity, make sure your file is saved and formatted correctly.
Change your name at the top of the activity. Replace
"Your Name"with your actual name wherever it appears at the beginning of the document.Give your files meaningful names. For example, use
RActivity1-YourName.qmdfor your Quarto file.Save all of your Quarto files in a dedicated folder for this class. Keep your
.qmdfile in a course folder so you can find it and continue working on it later.Check your work before submitting. Make sure you have answered all questions, included your R code, and written explanations wherever requested.
1.4 Rendering and Downloading Your .html File
You will submit the .html file, not the .qmd file, to Moodle. The ` file is the finished version of your activity, including your written answers, code, and plots.
Follow these steps in RStudio.
Save your work. Click the Save icon or select File > Save.
Render your document. Click the Render button near the top of the RStudio editor pane, where you write your Quarto document. Wait for the rendering process to finish. If errors appear, fix them before continuing.
Open the Files pane. In the lower-right pane of RStudio, click the Files tab and navigate to the folder where you stored your
.qmdfile. After rendering, The.htmlfile is saved in the same folder as your.qmdfile.Download the file. Check the box to the left of your
.htmlfile. Then, click the gear icon and More > Export. Download the file to your computer.Check your
.htmlfile before submitting. Open it and make sure your name, written answers, code, and plots appear correctly. Check that all questions are answered.
1.5 Submitting Your Activity to Moodle
1.6 Once you have rendered and downloaded your .html file, submit it on Moodle. Make sure that the file name follows to appropriate format.
2 Troubleshooting
Common errors and what they usually mean:
- Nothing ran, and the console shows
+: You may have an unclosed parenthesis, bracket, or quotation mark. Complete the expression or press Escape to cancel it. - Unexpected symbol: You may have forgotten a multiplication sign (
*) or included an invalid character. - Object not found: Check that you created the object first and spelled its name correctly. R is case-sensitive.
- Could not find function: Check that the package containing the function is loaded.
- Non-numeric argument to mathematical function: Check that your input is numeric and not text or a factor.
- Missing values (
NA): Check the data for missing values and consider whether the function you are using can handle them. - Error in
fitModel(): Check your formula, variable names, starting values, and whether the model is appropriate for the data. - Error in
makeFun(): Make sure the variables after~match the variables in the expression before it. - Quarto rendering fails: Check that your code runs, your packages are installed, and your document is properly formatted.
3 Functions and Expressions
3.1 Defining Variables
To define a variable, we use the following syntax:
The arrow tells RStudio to give the variable x the value of 5. Then we can ask RStudio what value is stored in x:
x[1] 5
3.2 Defining and Evaluating a Function with makeFun()
Use makeFun() from the mosaic package to create an R function from a mathematical expression.
The general syntax is:
f <- makeFun(EXPRESSION ~ INPUT)Examples:
f <- makeFun(x^2 + 5*x + 6 ~ x)
g <- makeFun(sin(x)^2 - 1/2 ~ x)
P <- makeFun(5 * exp(0.25*t) ~ t)
Q <- makeFun(12.38 * (1.041)^t ~ t)Notes: - Always use * for multiplication. - The variable on both sides of ~ must match (e.g., x^2 ~ x, not x^2 ~ t).
You can evaluate functions at specific input values:
f(-10)[1] 56
g(0)[1] -0.5
P(6)[1] 22.40845
Q(-1/2)[1] 12.13376
Reminders:
- Use
*for multiplication:3*x, not3x. - Use
^for exponents:x^2. - The variables in the expression must match the inputs after
~. - R distinguishes uppercase and lowercase letters:
xandXare different objects.
3.3 Common Mathematical Functions
| Mathematical expression | R command |
|---|---|
| \(x^2\) | x^2 |
| \(4x^2-7x+3\) | 4*x^2 - 7*x + 3 |
| \(\sqrt{x}\) | sqrt(x) or x^(1/2) |
| \(\sqrt[3]{x}\) | x^(1/3) |
| \(\sin(x)\) | sin(x) |
| \(\cos(x)\) | cos(x) |
| \(e^x\) | exp(x) |
| \(\ln(x)\) | log(x) |
| \(\log_{10}(x)\) | log10(x) |
| \(\log_b(x)\) | log(x, base = b) |
| \(|x|\) | abs(x) |
R uses radians for trigonometric functions.
3.4 Vectors (Lists) and Sequences
Use c() to combine values into a vector (aka a list) and seq() to create a sequence.
primes <- c(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
primes [1] 2 3 5 7 11 13 17 19 23 29
some_data <- c(5, -2, 7, 3, -10, 15)
some_data[1] 5 -2 7 3 -10 15
seq(1, 10) [1] 1 2 3 4 5 6 7 8 9 10
seq(5, 12, by = 0.5) [1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0 9.5 10.0 10.5 11.0 11.5 12.0
c()combines values into an ordered list.seq(from, to, by)generates a sequence wherebyspecifies the step size.
4 Single-Variable Functions
4.1 Plotting a Function with plotFun()
Use plotFun() to plot a function of one variable. You can specify the horizontal range using xlim.
plotFun(
sin(x) ~ x,
xlim = c(0, 2*pi)
)To plot a fitted model on top of a scatterplot, use add = TRUE.
plotPoints(gasbill ~ temp, data = Utilities)plotFun(
model(temp) ~ temp,
add = TRUE,
col = "red",
lwd = 2
)The data points show the observed values. The red curve represents the fitted model.
4.2 Plotting with slice_plot() and domain()
Use slice_plot() to plot a mathematical expression over a specified domain.
slice_plot(
sin(x) ~ x,
domain(x = 0:2*pi)
)The domain() function specifies the range of the input variable.
You can customize the plot with labels and colors:
slice_plot(
sin(x) ~ x,
domain(x = 0:2*pi),
color = "blue"
) +
xlab("x values") +
ylab("sin(x)") +
labs(title = "The sine function")For functions of one variable, plotFun() and slice_plot() are both useful.
5 Functions of Two Variables
A function of two variables has the form
\[ z=f(x,y). \]
The first input is the value of \(x\), and the second is the value of \(y\).
We can use makeFun() to define the function and then visualize it with surface plots, contour plots, and cross-sections.
5.1 Defining and Evaluating a Function with makeFun
Consider
\[ f(x,y)=x^2+y^2. \]
Define the function:
f <- makeFun(x^2 + y^2 ~ x & y)Evaluate it at particular points:
f(0, 0)[1] 0
f(-1, 5)[1] 26
5.2 Surface Plots: surface_plot()
A surface plot shows the height \(z=f(x,y)\) above each point in the \(xy\)-plane.
surface_plot(
f(x,y) ~ x & y,
domain(x = -10:10, y = -10:10)
)Loading required namespace: plotly
The domain specifies the ranges of both input variables.
5.3 Contour Plots: contour_plot()
A contour plot represents a function using curves in the \(xy\)-plane. Every point on the same contour curve has the same output value.
contour_plot(
f(x,y) ~ x & y,
domain(x = -10:10, y = -10:10),
skip = 0,
n_contours = 8
)Important arguments:
domain(): specifies the ranges ofxandy.skip = 0: prevents the plotting function from automatically skipping contour levels.n_contours = 8: requests 8 contour levels.
A contour plot is similar to a topographic map: each curve represents a constant height.
5.4 Cross-Sections: Fixing One Variable
A cross-section is created by fixing one variable and allowing the other to vary.
For example, if we fix \(y=4\), then
\[ f(x,4) = x^2 + (4)^2 = x^2 + 16 \]
The resulting function depends only on \(x\). Here is how you can plot it:
slice_plot(
f(x,4) ~ x,
domain(x = -10:10)
) +
ylab("f(x,4)")We can fix \(x=1\) and allow \(y\) to vary:
\[ f(1,y) = (1)^2+y^2=1+y^2. \] Notice that the function now depends only on \(y\). Here is the cross-section:
slice_plot(
f(1,y) ~ y,
domain(y = -10:10)
) +
ylab("f(1,y)")6 Working with Data
6.1 Useful Data Functions
| Function | Purpose | |
|---|---|---|
data() |
Load or list available data sets | |
head() |
Display the first rows of a data set | |
summary() |
Summarize variables | |
dataset$var |
Access the variable var from the data set called dataset |
|
diff() |
Calculate consecutive differences | |
log() |
Calculate natural logarithms | |
round() |
Round numerical values | |
print() |
Display a message or object | |
coef() |
Extract fitted model coefficients |
6.2 mosaicData Package Dataset List
Here is a list of built-in data sets and good candidates for input and output variables in the mosaic package:
| Dataset | Input variable | Output variable |
|---|---|---|
| Galton | father | height |
| Galton | mother | height |
| KidsFeet | length | width |
| CoolingWater | time | temp |
| Births2015 | day_of_year | births |
| Weather | date | avg_temp |
| Weather | date | high_temp |
| Weather | date | low_temp |
| SaratogaHouses | livingArea | price |
| SaratogaHouses | lotSize | price |
| TenMileRace | age | time |
| SnowGR | year | snow |
| Utilities | temp | usage |
6.3 Loading a Data Set
Use data() to load a built-in data set. The head command lets you see the first few rows of a data set.
data(Utilities)
head(Utilities) month day year temp kwh ccf thermsPerDay billingDays totalbill gasbill
1 12 29 1999 26 892 194 5.5 36 173.65 112.72
2 1 28 2000 18 533 164 5.6 30 139.18 95.88
3 2 26 2000 24 521 228 8.0 29 177.48 134.65
4 3 25 2000 41 554 16 0.6 28 61.27 15.32
5 4 28 2000 45 638 74 2.2 34 100.33 47.33
6 5 30 2000 60 700 129 4.1 32 153.32 89.87
elecbill notes
1 68.25
2 43.30
3 42.83
4 45.95 bad meter reading
5 53.00
6 63.45
Use $ to access a variable in a data frame. We save it to variables called temp and gasbill so that we can reuse the information.
temp <- Utilities$temp
gasbill <- Utilities$gasbillHere, temp represents outside temperature and gasbill represents the gas bill.
6.4 Summarizing Data
Use summary() to inspect the minimum, maximum, median, mean, and quartiles of a variable.
summary(temp) Min. 1st Qu. Median Mean 3rd Qu. Max.
9.00 30.00 51.00 48.66 69.00 78.00
summary(gasbill) Min. 1st Qu. Median Mean 3rd Qu. Max.
3.42 23.42 55.74 81.24 124.18 240.90
Summary statistics can help you identify reasonable starting values when fitting a model.
6.5 Plotting Data Points with plotPoints()
Use plotPoints() to create a scatterplot from a data frame. A data frame is a table of data, with rows and columns for x-values and y-values.
In this example, we are using gasbill as the input (x-values) and temp as the output (y-values).
plotPoints(temp ~ gasbill, data = Utilities)The formula temp ~ gasbill means that temp is plotted on the vertical axis and gasbill on the horizontal axis.
You can also create two vectors to use as your lists of x-values and y-values. They must have the same length.
x_data <- c(2, 3, 5, 8, 13, -4, 10)
y_data <- c(2, 4, 8, 4, 2, 5, 6)
plotPoints(y_data ~ x_data)A scatterplot helps you identify the general pattern in the data before choosing a model.
6.6 Fitting Models to Data
Use fitModel() from mosaic to estimate the parameters of a mathematical model.
The general syntax is:
model <- fitModel(
output ~ m*x + b,
data = Utilities,
start = list(parameter = starting_value)
)
coef(model)outputis the output variable.MODEL_EXPRESSIONdescribes the general function with parameters.dataidentifies the data frame (the table of data points).startprovides initial parameter guesses when needed for nonlinear models.
Here’s an example:
model <- fitModel(
temp ~ m*gasbill + b,
data = Utilities,
start = list(m=1, b=0)
)
coef(model) m b
-0.2839067 71.7239129
The required starting values depend on the model. Linear models generally do not require starting guesses, but nonlinear models often do.
6.7 Combining Data and Functions
When fitting a model, it is useful to show the original data and the fitted function on the same plot.
The process is:
- Plot the observed data with
plotPoints(). - Add the fitted function with
plotFun(add = TRUE). - Use a different color for the model.
For example:
plotPoints(gasbill ~ temp, data = Utilities)plotFun(
model(temp) ~ temp,
add = TRUE,
col = "red",
lwd = 2
)Use the plot to assess whether the model captures the overall pattern of the data.
7 Differentiation
7.1 Estimating Derivatives
Estimate derivative \(f'(x)\) numerically:
f <- makeFun(x^2 + 10*sin(x) ~ x)
h <- c(1, 0.1, 0.01, 0.001, 1e-4, 1e-5, 1e-6, 1e-7)
AROC <- (f(4 + h) - f(4)) / h
AROC[1] 6.978782 1.952538 1.511513 1.468349 1.464042 1.463612 1.463569 1.463564
The sequence should stabilize as h gets small.
7.2 Estimating Partial Derivatives
Estimate partial derivatives by varying one variable at a time:
g <- makeFun(exp(x * sin(y)) ~ x & y)
h <- c(1, 0.1, 0.01, 0.001, 1e-4, 1e-5, 1e-6, 1e-7)
# approximate gx(2,7)
gx_est <- (g(2 + h, 7) - g(2,7)) / h
# approximate gy(2,7)
gy_est <- (g(2, 7 + h) - g(2,7)) / h7.3 Gradient Search
Use gradient search by moving a small amount in the direction of the gradient:
partialx <- makeFun(-4*x^3 - 3*x^2 + 10*y ~ x & y)
partialy <- makeFun(10*x + 2 - 16*y ~ x & y)
newx <- 1; newy <- 1
slopex <- partialx(newx, newy)
slopey <- partialy(newx, newy)
newx <- newx + 0.1 * slopex
newy <- newy + 0.1 * slopeyRepeat these steps until the partial derivatives are near zero.
8 Optimization
Plot contours and constraints together to visualize constrained optimization problems:
P <- makeFun(x^(0.2) * y^(0.8) ~ x & y)
Q <- makeFun(4*x + 3*y ~ x & y)
contour_plot(
P(x,y) ~ x & y,
domain(x=0:80, y=0:80),
contours_at = seq(20,80,5),
skip=0
) |>
contour_plot(
Q(x,y) ~ x & y,
contour_color="black",
contours_at = c(200),
label_placement = 0.25)Scale for colour is already present.
Adding another scale for colour, which will replace the existing scale.
Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.
Zoom in for a better estimate and to approximate the Lagrange multiplier by changing the constraint by a small amount.
9 Integration
Approximate definite integrals by Riemann sums:
f <- makeFun(x + sin(x^2) ~ x)
a <- 5
b <- 10
base <- (b - a) / 100
points <- seq(from = a + base, to = b, by = base)
heights <- f(points)
areas <- base * heights
sum(areas)[1] 37.67298
Increase the denominator (e.g., to 1e6) for better accuracy.
Find the antiderivative of a function:
f <- makeFun(x^2 ~ x)
antiD(f(x) ~ x)function (x, C = 0)
x^3/3 + C
Compute the definite integral over an interval:
Integrate(f(x) ~ x, domain(x=0:10))Loading required namespace: cubature
[1] 333.3333
10 Differential Equations
10.1 Slope Fields and Trajectories
Plot slope fields with vectorfield_plot() and solution trajectories with traj_plot():
vectorfield_plot(
t ~ 1,
P ~ 6 - 2 * P,
domain(t=-8:8, P=-8:8)
)diff_eq <- makeODE(dP ~ 6 - 2 * P)
soln <- integrateODE(diff_eq, domain(t=0:5), P = 6)Solution containing functions P(t).
traj_plot(P(t) ~ t, soln, nt = 5)Plot vector field + multiple trajectories:
diff_eq <- makeODE(dP ~ 6 - 2 * P)
soln1 <- integrateODE(diff_eq, domain(t=0:5), P = 6)Solution containing functions P(t).
soln2 <- integrateODE(diff_eq, domain(t=0:5), P = 2)Solution containing functions P(t).
traj_plot(P(t) ~ t, soln1, color="blue", nt=5) |>
traj_plot(P(t) ~ t, soln2, color="magenta", nt=5) |>
vectorfield_plot(t ~ 1, P ~ 6 - 2 * P, domain(t=0:5, P=0:8))11 SIR Models
Use vectorfield_plot and makeODE to build SIR models:
a <- 0.001 # infection rate
b <- 0.2 # removal rate
vectorfield_plot(S ~ -a * S * I,
I ~ a * S * I - b * I,
domain(S = 0:800, I = 0:100),
transform = function(L) L^0.01)SIR_diff_eq <- makeODE(dS ~ -a * S * I, dI ~ a * S * I - b * I)
SIR_soln <- integrateODE(SIR_diff_eq, domain(t = 0:80), S = 800, I = 5)Solution containing functions S(t), I(t).
traj_plot(I(t) ~ S(t), SIR_soln, nt = 20)