2 + 3[1] 5
100 - 54[1] 46
10 / 4[1] 2.5
2^3[1] 8
(2 + 3) * 4[1] 20
16 %% 5[1] 1
COSC/MATH 201 · Fall 2026
R is the programming language we will use to build and explore models. This page collects the fundamentals from our first two class meetings. You do not need to memorize every detail; return here when you need a reminder.
Download the complete R script if you want to run these examples in Positron without copying them from the page.
Keep your work in an R script—a file ending in .R. Run a line or selected block to send it to the Console.
if block, including both braces, before running it.R can be used as a calculator. The operators +, -, *, /, and ^ perform familiar arithmetic. The %% operator gives the remainder after division. Parentheses control the order of operations.
A comment begins with #. R ignores comments, so use them to record meanings, units, and reasoning.
Use <- to assign a value to a name. Choose names that communicate what a value represents.
[1] 20
[1] 68
Names are case-sensitive. temperature_c and Temperature_C would be different names.
Changing an input does not automatically update an answer you calculated earlier. Run the calculation again:
[1] 68
[1] 77
R can store several kinds of values:
A vector stores multiple values of the same basic type. The c() function combines values, while : and seq() create sequences.
[1] 18 20 23 25 22
[1] 8 9 10 11 12
[1] 5
Use square brackets to select vector elements. R starts counting positions at 1.
[1] 18
[1] 20 23 25
[1] 18 23 22
[1] 8
head() and tail() select values from the beginning or end:
The colon operator creates consecutive integers, while seq() lets us choose the starting value, ending value, and step size:
R can apply one calculation to every value in a vector.
[1] 64.4 68.0 73.4 77.0 71.6
[1] 21.6
[1] 18
[1] 25
[1] 108
round() returns a rounded copy; it does not change temperatures_f. To keep rounded values, assign the result to an object. A calculation can also be valid R without being meaningful: sum(temperatures_c) works, but the sum is not a useful temperature measurement.
Give plot() horizontal coordinates first and vertical coordinates second. Always label axes and include units when they are known.

Use type = "o" to show both points and connecting lines. The lines show the order of the measurements; they do not create additional measurements.
A for loop repeats a block of code. This loop visits the values in a vector:
To save results, create an output vector and fill one position during each iteration.
[1] 64.4 68.0 73.4 77.0 71.6
Here, i represents a vector position. seq_along(temperatures_c) generates every valid position in temperatures_c.
We can check that the loop and the earlier vector calculation agree:
Comparisons produce TRUE or FALSE.
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
< and <= |
less than; less than or equal to |
> and >= |
greater than; greater than or equal to |
Remember: <- assigns a value, while == tests equality.
A logical vector can select the values whose comparisons are TRUE:
[1] 23 25
[1] 10 11
[1] 2
if and elseAn if statement chooses whether to run a block of code. Its condition must produce one TRUE or FALSE value.
[1] "The latest reading is at or below 22 degrees C."
The latest reading is exactly 22, so the else branch runs. > does not include equality.
Use any() or all() when a decision depends on several comparisons:
+ instead of >R is waiting for the rest of an incomplete expression. You may be missing a closing parenthesis, quote, or brace. Press Escape, repair the code in the script, and run the complete block again.
Select the entire block—including its opening and closing braces—before running it.
Check which object is on each axis, then rerun the calculations that create those objects.
---
title: "R Fundamentals"
subtitle: "COSC/MATH 201 · Fall 2026"
description-meta: "A concise introduction to the R fundamentals used in COSC/MATH 201."
format:
html:
toc: true
code-fold: false
code-overflow: wrap
code-tools: true
execute:
echo: true
warning: false
message: false
resources:
- r-fundamentals.R
---
R is the programming language we will use to build and explore models. This page collects the fundamentals from our first two class meetings. You do not need to memorize every detail; return here when you need a reminder.
::: {.callout-tip icon="false"}
## Download the code
[Download the complete R script](r-fundamentals.R){download="r-fundamentals.R"} if you want to run these examples in Positron without copying them from the page.
:::
## Working in Positron
Keep your work in an R script—a file ending in `.R`. Run a line or selected block to send it to the Console.
- The **script** records code you want to keep.
- The **Console** runs code and displays results.
- Run examples from top to bottom because later sections reuse earlier objects.
- Select an entire loop or `if` block, including both braces, before running it.
## Calculations and comments
R can be used as a calculator. The operators `+`, `-`, `*`, `/`, and `^` perform familiar arithmetic. The `%%` operator gives the remainder after division. Parentheses control the order of operations.
```{r}
2 + 3
100 - 54
10 / 4
2^3
(2 + 3) * 4
16 %% 5
```
A comment begins with `#`. R ignores comments, so use them to record meanings, units, and reasoning.
```{r}
60 * 60 # seconds in one hour
```
## Variables
Use `<-` to assign a value to a name. Choose names that communicate what a value represents.
```{r}
temperature_c <- 20 # degrees Celsius
temperature_f <- temperature_c * 9 / 5 + 32
temperature_c
temperature_f
```
Names are case-sensitive. `temperature_c` and `Temperature_C` would be different names.
Changing an input does not automatically update an answer you calculated earlier. Run the calculation again:
```{r}
temperature_c <- 25
temperature_f # still 68
temperature_f <- temperature_c * 9 / 5 + 32
temperature_f # now 77
```
R can store several kinds of values:
```{r}
class(temperature_c) # numeric
class("temperature") # character
class(TRUE) # logical
class(46L) # integer
```
## Vectors
A vector stores multiple values of the same basic type. The `c()` function combines values, while `:` and `seq()` create sequences.
```{r}
temperatures_c <- c(18, 20, 23, 25, 22)
hours <- 8:12
temperatures_c
hours
length(temperatures_c)
```
### Selecting values
Use square brackets to select vector elements. R starts counting positions at **1**.
```{r}
temperatures_c[1] # first value
temperatures_c[2:4] # positions 2 through 4
temperatures_c[c(1, 3, 5)] # selected positions
hours[1] # position 1 contains hour 8
```
`head()` and `tail()` select values from the beginning or end:
```{r}
head(temperatures_c, 2)
tail(temperatures_c, 2)
```
The colon operator creates consecutive integers, while `seq()` lets us choose the starting value, ending value, and step size:
```{r}
1:5
seq(from = 0, to = 2, by = 0.5)
```
### Calculating with vectors
R can apply one calculation to every value in a vector.
```{r}
temperatures_f <- temperatures_c * 9 / 5 + 32
round(temperatures_f, digits = 1)
mean(temperatures_c) # 21.6
min(temperatures_c) # 18
max(temperatures_c) # 25
sum(temperatures_c) # valid arithmetic, but not a useful temperature
```
`round()` returns a rounded copy; it does not change `temperatures_f`. To keep rounded values, assign the result to an object. A calculation can also be valid R without being meaningful: `sum(temperatures_c)` works, but the sum is not a useful temperature measurement.
## Graphs
Give `plot()` horizontal coordinates first and vertical coordinates second. Always label axes and include units when they are known.
```{r}
plot(
hours,
temperatures_c,
pch = 16,
xlab = "Hour of day",
ylab = "Temperature (degrees C)",
main = "Temperature readings"
)
```
Use `type = "o"` to show both points and connecting lines. The lines show the order of the measurements; they do not create additional measurements.
```{r}
plot(
hours,
temperatures_c,
type = "o",
pch = 16,
xlab = "Hour of day",
ylab = "Temperature (degrees C)"
)
```
## Loops
A `for` loop repeats a block of code. This loop visits the values in a vector:
```{r}
for (reading in temperatures_c) {
print(reading)
}
```
To save results, create an output vector and fill one position during each iteration.
```{r}
converted_f <- numeric(length(temperatures_c))
for (i in seq_along(temperatures_c)) {
converted_f[i] <- temperatures_c[i] * 9 / 5 + 32
}
converted_f
```
Here, `i` represents a vector position. `seq_along(temperatures_c)` generates every valid position in `temperatures_c`.
We can check that the loop and the earlier vector calculation agree:
```{r}
isTRUE(all.equal(converted_f, temperatures_f))
```
## Comparisons and decisions
Comparisons produce `TRUE` or `FALSE`.
| Operator | Meaning |
|:---:|:---|
| `==` | equal to |
| `!=` | not equal to |
| `<` and `<=` | less than; less than or equal to |
| `>` and `>=` | greater than; greater than or equal to |
Remember: `<-` assigns a value, while `==` tests equality.
```{r}
temperatures_c > 22
hours == 10
```
A logical vector can select the values whose comparisons are `TRUE`:
```{r}
temperatures_c[temperatures_c > 22]
hours[temperatures_c > 22] # hours 10 and 11
sum(temperatures_c > 22) # count matches: TRUE is 1, FALSE is 0
```
### `if` and `else`
An `if` statement chooses whether to run a block of code. Its condition must produce one `TRUE` or `FALSE` value.
```{r}
latest_reading <- tail(temperatures_c, 1)
if (latest_reading > 22) {
print("The latest reading is above 22 degrees C.")
} else {
print("The latest reading is at or below 22 degrees C.")
}
```
The latest reading is exactly 22, so the `else` branch runs. `>` does not include equality.
Use `any()` or `all()` when a decision depends on several comparisons:
```{r}
any(temperatures_c > 22)
all(temperatures_c > 22)
if (any(temperatures_c > 22)) {
print("At least one reading exceeds 22 degrees C.")
}
```
## Common problems
### “Object not found”
- Check the spelling and capitalization.
- Make sure you ran the line that creates the object.
- If needed, restart R and run the script from the top.
### The Console shows `+` instead of `>`
R is waiting for the rest of an incomplete expression. You may be missing a closing parenthesis, quote, or brace. Press **Escape**, repair the code in the script, and run the complete block again.
### A loop or decision does not run correctly
Select the entire block—including its opening and closing braces—before running it.
### A graph has the wrong values
Check which object is on each axis, then rerun the calculations that create those objects.