🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Python and R for Data Science & Analytics › Lesson 3
TEC-DATA85-03 · Lesson 3 · 12 clock hours · theory

R Syntax, Vectors, and Data Frames

Objective. Students write R scripts that create and manipulate vectors, factors, lists, and data frames to represent and access structured tabular data.

⚠ Pending professional review

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.

What Is R and Why Use It for Data Science?

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 Syntax Basics

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.

Vectors

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).

Factors

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.

Lists

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"

```

Data Frames

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

```

Importing and Inspecting CSV Data

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 and dplyr

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.

R Markdown and Reproducibility

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.

Workplace and Data Safety Notes

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.

Key terms8

VectorR's basic one-dimensional data structure that stores a sequence of values of the same type, created with c().
FactorA vector that stores categorical data as integer codes with named levels, used to represent variables with a fixed set of categories.
Data FrameR's tabular data structure where each column is a vector of the same length; columns may be different types, representing variables across observations.
dplyrA tidyverse package providing a set of readable verb functions — such as filter(), mutate(), and summarize() — for manipulating data frames.
R MarkdownA document format (.Rmd) that combines narrative text with executable R code chunks and knits them into a reproducible HTML, PDF, or Word report.
str()An R function that compactly displays the internal structure of an object, showing column names, data types, and sample values for a data frame.
Pipe OperatorThe |> (base R) or %>% (magrittr) operator that passes the result of one expression as the first argument of the next, enabling readable chains of dplyr verbs.
CoercionR's automatic conversion of values to a common data type when a vector contains mixed types, following a hierarchy from logical to integer to numeric to character.
In class: Follow a live-coded demo in RStudio to build a data frame from scratch using vectors of mixed types (numeric, character, logical, factor); add a new computed column and subset rows using bracket notation and the subset() function. · Import a provided CSV file of state-level demographic data using read.csv(), inspect it with str(), head(), and summary(), and answer 10 written questions about the data structure (column types, row count, missing value flags). · Rewrite the same data-frame operations using dplyr verbs (select, filter, mutate, arrange, summarize) and compare the output line by line with the base-R approach in a side-by-side R Markdown document.
Materials: RStudio, R documentation (r-project.org), tidyverse package (tidyverse.org), provided CSV dataset, R Markdown template, lab log
Check: R Markdown document knits without errors; 8 of 10 inspection questions answered correctly; dplyr output matches base-R output for all operations — pass requires both conditions met.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data wrangling and manipulation
1. Which R function is used to combine multiple values into a vector?
Data types and structures
2. A data frame column is created as factor(c('Low','High','Medium','High')). How many levels does this factor have?
Exploratory data analysis
3. What does the str() function return when applied to a data frame?
Data wrangling and manipulation
4. In base R, what does the expression df[df$score > 80, ] return?
Data wrangling and manipulation
5. Which dplyr verb is equivalent to adding a new computed column to a data frame?
Data types and structures
6. When R encounters c(1, 2, 'three') and stores it, what type will all three elements become?
Reporting and data storytelling
7. An analyst knits an R Markdown document and receives an error. What is the most likely professional reason to resolve this before sharing the report?
Exploratory data analysis
8. A data analyst loads a CSV file with read.csv() and runs summary() on the result. She notices an NA count listed under one column. What does this indicate?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.