Skip to contentSkip to lesson map

Computing and Graphing in R

Reading
MMAC Ch 1.1, pp 12-15
Practice
Optional HW 2 Q4.2, Q5.3, and Q9.1.
Lesson map

Objectives

  1. Create an RScript, add and run lines of code, and save it.
  2. Understand the difference between running code from the console versus an RScript, and when to use each.
  3. Run code by (a) ctrl+enter, (b) highlighting multiple lines and running all, (c) the “Run” button.
  4. Use makeFun() to define a function and plotFun() to plot one.
  5. Evaluate a previously defined function at a given input.
  6. Use plotPoints() to graph data from a dataset.
  7. Understand common R error messages to help debug your code.

Getting Started

  1. Log in to posit.cloud.
  2. Open the Math 141 Fall 2026 Base Workspace.

1. RScripts

Objective. Create an RScript, add and run lines of code, and save it.

Creating and saving an RScript.

  1. Choose File →\rightarrow New File →\rightarrow R Script. An empty RScript opens in the top left pane.
  2. Type one command per line.
  3. Run each line with Ctrl+Enter (section 3).
  4. Press Ctrl+S, type a name such as Lesson 2, and click Save. The file appears in the Files tab as Lesson 2.R.
  5. Press Ctrl+S again after every change. RStudio shows the name of an unsaved RScript in red on its tab.

Commenting a script. R ignores the rest of a line after the character #.

Example 1

Two numbers are defined by

a=cos⁡(4π)⋅23,b=(ln⁡4)3+3e. a = \cos(4\pi)\cdot\sqrt[3]{2}, \qquad b = (\ln 4)^3 + 3^e.

Create an RScript named Lesson 2 that computes aa, bb, and b/ab/a, and save it.

ShowHide solution

Choose File →\rightarrow New File →\rightarrow R Script, then type:

# Math 141 - Lesson 2 - Computing and Graphing in R
a = cos(4*pi) * 2^(1/3)
b = log(4)^3 + 3^exp(1)
b/a

Highlight the four lines and press Ctrl+Enter. R skips the comment line and stores a and b in the Environment. The last line prints [1] 17.84016, which gives b/a≈17.840b/a \approx 17.840. Save the file with Ctrl+S.

Example 2

A runner covers 26.2 miles in 3.5 hours. Create and save an RScript named Speed that stores the distance and the time and computes the average speed in miles per hour.

ShowHide solution

Choose File →\rightarrow New File →\rightarrow R Script, then type a comment line and one command per line:

# Average speed in miles per hour
distance = 26.2
time = 3.5
distance/time

Put the cursor on the first line and press Ctrl+Enter four times, once per line. The two assignment lines store distance and time in the Environment, and the last line prints [1] 7.485714, an average speed of about 7.486 miles per hour. Press Ctrl+S, type Speed, and click Save. The Files tab then lists Speed.R.

RScript download from Posit Cloud.

  1. Open the Files tab at the bottom right and tick the box beside the .R file.
  2. Click the gear icon labeled More, then Export, then Download.

Next: 2. Console and RScriptLesson map

2. Console and RScript

Objective. Understand the difference between running code from the console versus an RScript, and when to use each.

A line gives the same result whether it runs from the Console or from an RScript (both defined on the Lesson 1 sheet, section 1). In both cases R prints the output, when there is one, in the Console. Only the RScript saves its lines in a file.

Console. Use the Console for a one-off calculation, a help page such as ?plotFun, or a quick look at a dataset. Lines typed there are kept in the History and in no file.

RScript. Use the RScript for homework, class work, and every line worth running again. The saved .R file is the record of the work. Submit the .R file to Gradescope.

Example 3

Choose the Console or an RScript for each task.

  • (a) Open the help page for plotFun.
  • (b) Write the lines for a homework problem that goes to Gradescope.
  • (c) Check the value of 2102^{10} once.
ShowHide solution
  • (a) The Console, because ?plotFun is a one-off look at a help page.
  • (b) An RScript, because the homework lines must be saved and submitted as the .R file.
  • (c) The Console, because 2^10 is a one-off calculation. The line prints [1] 1024.

Example 4

Two lines typed in the Console compute the area of a circle of radius 3:

r = 3
pi*r^2

Keep the two lines so that they can run again in a later session.

ShowHide solution

The Console keeps its lines only in the History, and an RScript keeps its lines in a file. Open a new RScript with File →\rightarrow New File →\rightarrow R Script. In the History pane, select the two lines and click To Source, which copies them into the open RScript. Save the RScript with Ctrl+S. In a later session, the two lines run from the RScript store r and print [1] 28.27433, the area 9π≈28.2749\pi \approx 28.274.

Next: 3. Ways to Run CodeLesson map

3. Ways to Run Code

Objective. Run code by (a) ctrl+enter, (b) highlighting multiple lines and running all, (c) the “Run” button.

  1. One line. Put the cursor anywhere on the line and press Ctrl+Enter. The cursor then moves to the next line. Press Ctrl+Enter again to run the next line.
  2. Several lines. Highlight the lines, then press Ctrl+Enter. To run the whole script, highlight it all with Ctrl+A first.
  3. Run button. Click Run on the RScript pane’s toolbar. The button runs the line the cursor is on, or the highlighted lines.

Example 5

An RScript contains three lines:

w = 12
h = 5
w*h

Run the lines one at a time.

ShowHide solution

Put the cursor on the line w = 12 and press Ctrl+Enter. R stores w, and the cursor moves to h = 5. Press Ctrl+Enter again to store h, then once more to run w*h, which prints [1] 60, because 12⋅5=6012 \cdot 5 = 60.

Example 6

An RScript contains the two lines r = 3 and pi*r^2. Run both lines at once, first with the keyboard and then with the Run button.

ShowHide solution

Press Ctrl+A to highlight the whole script, then press Ctrl+Enter. R runs the lines in order, and the Console prints [1] 28.27433. With the lines still highlighted, click Run on the RScript pane’s toolbar. R runs the same two lines and prints the same result.

Next: 4. Function Definitions and PlotsLesson map

4. Function Definitions and Plots

Objective. Use makeFun() to define a function and plotFun() to plot one.

Take f(x)=3x+2f(x) = 3x + 2. Its name is ff, its input is xx, its output is f(x)f(x), and its formula is 3x+23x + 2.

The functions makeFun, plotFun, and plotPoints each take a tilde expression, with the output to the left of the ~ and the input to the right. For makeFun and plotFun, the output is a formula such as 3*x + 2. The ~ key sits above the Tab key.

TaskPatternExample
Define a functionname = makeFun(formula ~ input)f = makeFun(3*x + 2 ~ x)
Plot a named functionplotFun(name(x) ~ x)plotFun(f(x) ~ x)
Plot a formula directlyplotFun(formula ~ x)plotFun(3*x + 2 ~ x)

Name the function with makeFun first when it will be evaluated or plotted more than once.

Naming a function. The naming rules for values in the Lesson 1 sheet, section 3, apply to functions too. Case sensitivity and the reuse of a name work the same way. In the Environment, the Functions heading sits below the Values heading and lists each function.

Options follow the tilde expression inside the parentheses. Each is written name = value, with a comma before it:

plotFun(x^2 ~ x, xlim = c(-5, 5), col = "red")

An option left out takes its default value. In xlim = c(-5, 5), the vector c(-5, 5) gives the two ends of the range.

OptionMeaningExample
xlimthe x range shownxlim = c(-5, 5)
ylimthe y range shownylim = c(0, 20)
colthe curve colorcol = "red"
lwdthe line widthlwd = 3
ltythe line type (5 is long dashes)lty = 5
adddrawing onto the existing plotadd = TRUE

Adding to a plot. With add = TRUE, plotFun draws the new curve onto the existing plot. Without it, each plotFun call replaces the plot. The first plotting call never carries add = TRUE, because an empty Plots pane has no plot to add to.

The window of a plot is the range of xx values and yy values it shows. A curve added with add = TRUE keeps the window of the first plot and shows only the part that falls inside it. To fit every curve, set a wide enough window with xlim and ylim on the first call.

Example 7

Define the function

f(x)=x2 f(x) = x^2

and plot it on −4≤x≤4-4 \le x \le 4.

ShowHide solution

Define ff with makeFun, then plot it with xlim set to the interval:

f = makeFun(x^2 ~ x)
plotFun(f(x) ~ x, xlim = c(-4, 4))

The plot is a parabola with its lowest point at (0,f(0))=(0,0)(0, f(0)) = (0, 0). At both edges of the window the height is 16,

f(−4)=(−4)2=16,f(4)=42=16, f(-4) = (-4)^2 = 16, \qquad f(4) = 4^2 = 16,

the points (−4,16)(-4, 16) and (4,16)(4, 16). Without xlim, R picks its own window, here −1.5≤x≤1.5-1.5 \le x \le 1.5.

Figure

Example 8

For the functions

g(x)=esin⁡(x),f(x)=x2,h(x)=4cos⁡(x−4)+f(x), g(x) = e^{\sin(x)}, \qquad f(x) = x^2, \qquad h(x) = 4\cos(x - 4) + f(x),

plot gg on −6≤x≤3-6 \le x \le 3 in cyan. Then add hh to the same plot, with hh defined in terms of ff.

ShowHide solution

Define the three functions, with f(x) in place of x2x^2 in the formula for h, then plot gg and add hh:

g = makeFun(exp(sin(x)) ~ x)
f = makeFun(x^2 ~ x)
h = makeFun(4*cos(x - 4) + f(x) ~ x)
plotFun(g(x) ~ x, xlim = c(-6, 3),
col = "cyan")
plotFun(h(x) ~ x, add = TRUE)

Figure

Because the call for gg sets no ylim, R fits the window to the values of gg. On −6≤x≤3-6 \le x \le 3, sin⁡(x)\sin(x) takes every value from −1-1 to 11, and the values of gg run from e−1e^{-1} to ee. The curve of hh appears only where its values fall inside that range, the two short blue pieces labeled hh.

Example 9

Without makeFun, plot the function

y=x2−3x+3 y = x^2 - 3x + 3

on −5≤x≤5-5 \le x \le 5 and −2≤y≤10-2 \le y \le 10. Then add these two curves to the same plot, the first in red:

y=cos⁡ ⁣(1x),y=sin⁡2(x)+cos⁡2(x). y = \cos\!\left(\frac{1}{x}\right), \qquad y = \sin^2(x) + \cos^2(x).
ShowHide solution

Plot the first function with xlim and ylim set, then add each curve with add = TRUE, writing sin⁡2(x)\sin^2(x) as sin(x)^2:

plotFun(x^2 - 3*x + 3 ~ x,
xlim = c(-5, 5), ylim = c(-2, 10))
plotFun(cos(1/x) ~ x, add = TRUE,
col = "red")
plotFun(sin(x)^2 + cos(x)^2 ~ x,
add = TRUE)

Figure

The second added curve is the flat line y=1y = 1, because sin⁡2(x)+cos⁡2(x)=1\sin^2(x) + \cos^2(x) = 1 for every xx. The red curve oscillates between −1-1 and 11 faster and faster near x=0x = 0.

Next: 5. Function EvaluationLesson map

5. Function Evaluation

Objective. Evaluate a previously defined function at a given input.

TaskPatternExample
Evaluate a functionname(input)f(9)

The input can be a calculation as well as a number. To evaluate ff at ee, type f(exp(1)), because R has no stored name e. To evaluate ff at π\pi, type f(pi).

Inputs with no output. An input at which R prints NaN, or prints Inf because of a division by zero, is an input where the formula has no real output (Lesson 1 sheet, section 2, for both values). The one exception is an odd root of a negative number, at the end of this section. A homework answer at an input with no output is Not Applicable.

Example 10

Define the function

g(x)=esin⁡(x) g(x) = e^{\sin(x)}

and evaluate it at x=0x = 0, x=2x = 2, and x=5x = 5.

ShowHide solution

Define gg with makeFun, then evaluate it at each input:

g = makeFun(exp(sin(x)) ~ x)
g(0)
g(2)
g(5)

The last three lines print [1] 1, [1] 2.482578, and [1] 0.383305, which give g(0)=1g(0) = 1, g(2)≈2.483g(2) \approx 2.483, and g(5)≈0.383g(5) \approx 0.383. The value g(0)=1g(0) = 1 agrees with the definition:

g(0)=esin⁡(0)=e0=1. g(0) = e^{\sin(0)} = e^0 = 1.

Example 11

For the functions

f(x)=x2,h(x)=4cos⁡(x−4)+f(x), f(x) = x^2, \qquad h(x) = 4\cos(x - 4) + f(x),

define hh in terms of ff and evaluate hh at x=3x = 3.

ShowHide solution

Define ff, then hh with f(x) in place of x2x^2 as in Example 8, and evaluate:

f = makeFun(x^2 ~ x)
h = makeFun(4*cos(x - 4) + f(x) ~ x)
h(3)

The last line prints [1] 11.16121, which gives h(3)≈11.161h(3) \approx 11.161.

Example 12

Define the function

k(x)=x2+3x−1 k(x) = x^2 + 3x - 1

and evaluate it at x=ex = e and x=πx = \pi.

ShowHide solution

Define kk, then evaluate it with exp(1) for ee and pi for π\pi:

k = makeFun(x^2 + 3*x - 1 ~ x)
k(exp(1))
k(pi)

The last two lines print [1] 14.5439 and [1] 18.29438. Rounded to three decimal places, the values are k(e)≈14.544k(e) \approx 14.544 and k(π)≈18.294k(\pi) \approx 18.294.

Example 13

Define the function

p(x)=xx−4 p(x) = \frac{\sqrt{x}}{x - 4}

in R and evaluate it at x=9x = 9, x=4x = 4, and x=−1x = -1.

ShowHide solution

Define pp, then evaluate it at each input:

> p = makeFun(sqrt(x)/(x - 4) ~ x)
> p(9)
[1] 0.6
> p(4)
[1] Inf
> p(-1)
[1] NaN
Warning message:
In sqrt(x) : NaNs produced

The first value is exact, p(9)=0.6p(9) = 0.6. The value p(4)p(4) is undefined, because the denominator is 4−4=04 - 4 = 0, and R prints Inf because the numerator is 4=2\sqrt{4} = 2. The value p(−1)p(-1) is undefined, because −1-1 has no real square root, and R prints NaN. As homework answers, p(4)p(4) and p(−1)p(-1) are Not Applicable.

Odd roots of negative inputs. R returns NaN for an odd root of a negative input written as a fractional power, although that root is a real number (Lesson 1 sheet, section 2). A plot of x^(1/3) shows no curve left of zero.

Next: 6. Graphs of DataLesson map

6. Graphs of Data

Objective. Use plotPoints() to graph data from a dataset.

TaskPatternExample
Plot typed-in dataplotPoints(output ~ input)plotPoints(y ~ x)
Plot a stored datasetplotPoints(output ~ input, data = name)plotPoints(Average ~ Year, data = MaunaLoaCO2)
Look up a command or dataset?name?MaunaLoaCO2
List a dataset’s columnsnames(name)names(MaunaLoaCO2)
See a dataset’s first and last rowshead(name), tail(name)head(MaunaLoaCO2)

Typed-in data. The function c() makes a vector, a list of numbers in order. One vector lists the inputs and one lists the outputs:

x = c(1, 5, 4)
y = c(4, 8, 11)
plotPoints(y ~ x)

The last line plots (1,4)(1, 4), (5,8)(5, 8), and (4,11)(4, 11). The first entries of x and y, 1 and 4, make the first point, the second entries make the second point, and the third entries make the third. The two vectors have to be the same length and in matching order.

Course datasets. The help page from ?MaunaLoaCO2 describes the data and its units. The tilde expression names columns of the dataset, and names(MaunaLoaCO2) lists the column names.

With the option data =, R finds the columns in that dataset. Without it, R looks for the names Average and Year in the Environment and stops with an error:

> plotPoints(Average ~ Year)
Error in eval(i, data, env) : object 'Average' not found

Lowest and highest values. The input of the lowest or highest point is the value on the horizontal axis directly below or above the point.

Exact lowest and highest values.

  1. Type View(MaunaLoaCO2) in the Console. R opens the dataset as a table.
  2. Click a column header. R sorts the rows by that column, smallest first.
  3. Click the header a second time. R sorts the rows largest first.

Options such as add = TRUE, ylim, and col work with plotPoints as they do with plotFun.

Example 14

Plot the points (0,3)(0, 3), (4,10)(4, 10), (−3,5)(-3, 5), (6,1)(6, 1), and (1/2,1/2)(1/2, 1/2). Add the line

y=3x+2 y = 3x + 2

in magenta, then add the points (0,4)(0, 4), (1,2)(1, 2), (2,0)(2, 0), and (3,−2)(3, -2).

ShowHide solution

Store and plot the first points and add the line. Then store the second points under the new names x2 and y2, which leaves x and y unchanged, and add them:

x = c(0, 4, -3, 6, 1/2)
y = c(3, 10, 5, 1, 1/2)
plotPoints(y ~ x, ylim = c(-3, 11))
plotFun(3*x + 2 ~ x, add = TRUE,
col = "magenta")
x2 = c(0, 1, 2, 3)
y2 = c(4, 2, 0, -2)
plotPoints(y2 ~ x2, add = TRUE)

Figure

The figure draws the first five points as open circles and the second four as filled dots, with the line y=3x+2y = 3x + 2 in magenta. R draws both sets with the same marker. The ylim on the first call makes room for (3,−2)(3, -2). The default window, set from the first five points, stops just below y=0y = 0 and leaves that point out.

Example 15

The MaunaLoaCO2 dataset records the yearly average carbon dioxide level at Mauna Loa, Hawaii. Its columns include Year and Average. Plot Average against Year.

ShowHide solution

Open the help page, list the column names, and plot with data = naming the dataset:

?MaunaLoaCO2
names(MaunaLoaCO2)
plotPoints(Average ~ Year, data = MaunaLoaCO2)

On the help page, Average is in parts per million by volume. Each row of the dataset becomes one point. The tilde expression Average ~ Year puts the output Average on the vertical axis and the input Year on the horizontal axis. The plot has one point per year, and the points rise from each year to the next.

Next: 7. Common ErrorsLesson map

7. Common Errors

Objective. Understand common R error messages to help debug your code.

Wrong spelling or case. The functions plotFun and makeFun carry a capital in the middle. R reads plotfun as a different name from plotFun.

> plotfun(x^2 ~ x)
Error in plotfun(x^2 ~ x) : could not find function "plotfun"

Line never run. The message quotes the missing name. Run the line that stores the missing function or vector.

> plotFun(f(x) ~ x)
Error in f(x) : could not find function "f"
> plotPoints(y ~ x)
Error in eval(i, data, env) : object 'y' not found

Missing ~ x. R reports only that it cannot find the object x.

> makeFun(x^2)
Error: object 'x' not found

The fix is makeFun(x^2 ~ x).

Mismatched parentheses. The Lesson 1 sheet, section 1, covers the + prompt and Esc. Clicking a parenthesis in RStudio lights up its partner.

Tilde inside the formula. The message quotes the function that failed. The tilde separates the whole formula from the input.

> g = makeFun(sin(x ~ x))
Error in sin(x ~ x) : non-numeric argument to mathematical function
> g(9)
Error in g(9) : could not find function "g"

The failed line stores nothing. R then prints that it cannot find g. The fix is g = makeFun(sin(x) ~ x).

Troubleshooting.

  1. Read the message.
  2. Check the line named in the message for spelling, capitals, the tilde, and the parentheses.
  3. Clear the Environment with the broom in the Environment pane, then run the script again from the top.
  4. Choose Session →\rightarrow Restart R, then run the script again from the top.
  5. Clear stuck plots with the broom in the Plots pane.
  6. Choose Relaunch project from the ... menu at the top right of Posit Cloud.

Example 16

Two lines of an RScript define the function

g(x)=sin⁡(x) g(x) = \sin(x)

and evaluate it at x=9x = 9. Both lines are highlighted and run:

> g = makeFun(sin(x) ~ x
+ g(9)
Error: unexpected symbol in:
"g = makeFun(sin(x) ~ x
g"

Identify the error.

ShowHide solution

The first line is missing its closing parenthesis. With the + prompt, R reads the second line as more of the first. Inside the open makeFun(, R cannot read the line past g and stops there. The fix is g = makeFun(sin(x) ~ x).

Example 17

Two plotFun lines are written for sin⁡(x)\sin(x) and cos⁡(x)\cos(x) on the same axes, the first in magenta and the second in cyan:

> plotFun(sin(x) ~ x, xlim = c(-3, 3), "magenta")
Error in multiple && !outer : invalid 'x' type in 'x && y'
> plotFun(cos(x) ~ x, TRUE, "cyan")
Error in !outer : invalid argument type

Identify the error.

ShowHide solution

The color and add options have no names. Without col = and add =, R hands "magenta", TRUE, and "cyan" to other options of plotFun. Each error comes from one of those options. Naming each option gives the two corrected commands:

plotFun(sin(x) ~ x, xlim = c(-3, 3), col = "magenta")
plotFun(cos(x) ~ x, add = TRUE, col = "cyan")

Example 18

Two lines of an RScript define and plot the function

j(x)=x6−x3. j(x) = x^6 - x^3.

j = makeFun(x^6 - x^3 ~ x)
plotFun(j(x) ~ x)

The plot never appears, and the Console shows this error:

Error in j(x) : could not find function "j"

Identify what happened.

ShowHide solution

The makeFun line was typed but never run. When the plotFun line ran, R found no function j in the Environment. Run the makeFun line first, then the plotFun line.

Lesson map