Objective. Students write R scripts that create and manipulate vectors, factors, lists, and data frames to represent and access structured tabular data.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
R is a free, open-source programming language designed specifically for statistical computing and data visualization. It is widely used by data analysts, statisticians, and data scientists in industry, government, and research. R runs best inside RStudio, an integrated development environment (IDE) that provides a script editor, console, environment pane, and output viewer in one window. When you work in RStudio, always save your scripts regularly and keep your working directory organized so that file paths remain predictable and reproducible.
R is case-sensitive. Variable names cannot start with a number and should not contain spaces. The assignment operator is `<-` (preferred) or `=`. Comments begin with `#`. Every statement that produces output will print to the console unless you suppress it or assign the result to a variable.
```r
x <- 42
greeting <- "Hello, data!"
print(greeting)
```
R executes code line by line. When you write scripts (`.R` files) or R Markdown documents (`.Rmd` files), you can run the entire file or individual chunks.
A vector is the most fundamental data structure in R. It stores a sequence of values of the same data type. You create a vector with the `c()` (combine) function.
```r
ages <- c(23, 45, 31, 27) # numeric
names_vec <- c("Ana", "Ben", "Cara") # character
flags <- c(TRUE, FALSE, TRUE) # logical
```
R will coerce mixed types to the most general type if you mix them in one vector, so keep types consistent. Access elements with bracket notation: `ages[2]` returns the second element (R uses 1-based indexing, not 0-based).
A factor stores categorical data as integer codes with associated labels called levels. Factors are important when working with demographic groups, survey responses, or any variable with a fixed set of categories.
```r
region <- factor(c("North", "South", "North", "West"))
levels(region) # returns "North" "South" "West"
```
Factors are memory-efficient and many statistical models in R require them to handle categorical predictors correctly.
A list can hold elements of different types, including other vectors, data frames, or even other lists. Lists are useful for storing heterogeneous results, such as the output of a model or a set of configuration values.
```r
record <- list(id = 101, name = "Ana", enrolled = TRUE)
record$name # access by name: returns "Ana"
record[[2]] # access by position: returns "Ana"
```
A data frame is R's primary structure for tabular data. Think of it as a spreadsheet: rows are observations and columns are variables. Each column is a vector, and all columns must have the same length. Columns can hold different types, making data frames more flexible than a plain matrix.
```r
df <- data.frame(
name = c("Ana", "Ben", "Cara"),
age = c(23, 45, 31),
active = c(TRUE, FALSE, TRUE)
)
```
Add a computed column with the `$` operator:
```r
df$age_group <- ifelse(df$age >= 30, "Senior", "Junior")
```
Subset rows with bracket notation or with `subset()`:
```r
df[df$age > 25, ] # bracket notation
subset(df, age > 25, select = name) # subset() function
```
Use `read.csv()` to load a comma-separated file into a data frame:
```r
states <- read.csv("state_demographics.csv")
```
Always inspect a new data frame immediately:
The tidyverse is a collection of R packages that share a consistent design philosophy. The dplyr package within tidyverse provides readable verbs for data manipulation:
| Verb | What it does |
|---|---|
| `select()` | Keep or drop columns |
| `filter()` | Keep rows matching a condition |
| `mutate()` | Add or modify columns |
| `arrange()` | Sort rows |
| `summarize()` | Aggregate rows into summary values |
Verbs are chained with the pipe operator `|>` (base R) or `%>%` (magrittr, loaded with tidyverse):
```r
library(tidyverse)
states |>
filter(population > 1000000) |>
mutate(pop_millions = population / 1e6) |>
arrange(desc(pop_millions)) |>
select(state, pop_millions)
```
The output is identical to equivalent base-R bracket operations but is often easier to read and debug.
An R Markdown document (`.Rmd`) weaves narrative text, R code chunks, and their output into a single report. When you click Knit, RStudio runs every code chunk from top to bottom in a fresh session and produces an HTML, PDF, or Word document. If the document knits without errors, it confirms your code is reproducible — a core professional standard in data analytics.
Data science carries important professional obligations even without physical hazards. Always protect personally identifiable information (PII): never write raw PII to unencrypted files or commit it to public repositories. Verify file paths before reading or writing data to avoid overwriting source files. Keep backups of raw data files; treat them as read-only. When sharing R Markdown reports containing real data, confirm that your institution's data governance policy permits distribution before sending.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.