Unit 12: R Tool

ECAP792 2 min read

I. Foundations of R

R is an open-source programming language and environment for statistical computing, data analysis, and graphics. Developed by Ross Ihaka and Robert Gentleman in the early 1990s, it draws heavily on the S language and is maintained through the GNU Project and the wider R community.

Defining characteristics:

  • Statistical orientation: R provides built-in facilities for descriptive statistics, modelling, hypothesis testing, simulation, and visualization.
  • Interpreted execution: Commands are evaluated by the R interpreter without a separate compilation stage.
  • Vectorized operation: A single expression can operate on every element of a vector, reducing the need for explicit loops.
  • Open-source ecosystem: Base R can be extended with packages distributed through repositories such as the Comprehensive R Archive Network (CRAN).
  • Object-based workspace: Values such as vectors, functions, models, and data frames are stored as named objects.
  • Case sensitivity: score, Score, and SCORE are three different names.
  • One-based indexing: The first element of an object has position 1, not position 0.

A. Introduction to R

R combines a programming language with an interactive environment in which data can be imported, transformed, analysed, and presented.

  • Interactive commands: Expressions entered at the console are evaluated immediately; for example, 2 + 3 returns 5.
  • Assignment: The operator <- conventionally stores a value under a name.
R
radius <- 4
area <- pi * radius^2
area
  • Named objects: Here, radius stores 4, pi is R’s built-in constant, and area stores the calculated circle area.
  • Functions: Operations are commonly expressed as function calls such as mean(x), where x is the supplied data object.
  • Comments: Text following # is ignored during execution and documents the program.
  • Help system: ?mean opens documentation for mean(), while help.search("regression") searches help pages by topic.
  • Packages: install.packages("ggplot2") installs a package once; library(ggplot2) attaches it in the current session.
  • Working environment: getwd() reports the current working directory, and ls() lists objects in memory.
  • Missing values: NA represents an unavailable value; calculations may require an option such as mean(x, na.rm = TRUE).

II. RStudio — Integrated Development Environment

RStudio is an integrated development environment (IDE) for working with R. It does not replace the R language or interpreter; instead, it provides an organized interface for writing code, running analyses, viewing results, and managing projects.

A. RStudio

RStudio improves the development workflow by placing commonly used R tools within a multi-pane interface.

  • Source pane: Holds reusable scripts, typically saved with the .R extension; selected lines can be sent to the console for execution.
  • Console pane: Displays the > prompt, executes commands, prints results, and reports warnings or errors.
  • Environment pane: Shows currently defined objects, including their names, types, dimensions, and values.
  • History pane: Records previously executed commands so that they can be reviewed or reused.
  • Files pane: Supports navigation through project folders and files.
  • Plots pane: Displays graphics created by commands such as plot(x, y) or hist(x).
  • Packages pane: Lists installed packages and allows them to be attached or detached.
  • Help pane: Presents R documentation within the IDE.
  • Projects: An .Rproj project associates scripts, data, and output with a particular working directory, making analyses easier to organize and reproduce.
  • Script-based workflow:
    1. Write commands in a script rather than relying only on console history.
    2. Run and inspect small sections during development.
    3. Save the script so the full analysis can be repeated.
  • Distinction: R is the language and computational engine; RStudio is an optional interface, now developed by Posit, for using that engine efficiently.

III. Data Objects and Organization

R stores information in data structures whose dimensions and element-type rules determine which operations are valid. Selecting the correct structure makes an analysis clearer and reduces unintended type conversion.

A. Important R data structures

The principal R data structures differ according to dimensionality and whether their elements must share one atomic type.

  • Atomic types: Common basic types include logical, integer, double, character, complex, and raw.
  • Homogeneous structures: Atomic vectors and matrices contain elements of one common type.
  • Heterogeneous structures: Lists can contain unrelated types and differently shaped objects.
  • Rectangular structures: Data frames organize equal-length columns into rows and columns.
  • Attributes: Objects may carry metadata such as names, dim, class, or row names.
  • Type inspection: typeof(x) identifies internal storage, class(x) reports object-oriented class, and str(x) gives a compact structural display.
  • Coercion hierarchy: Mixing logical, numeric, and character values in an atomic vector generally converts them to a type capable of holding all values.
R
x <- c(TRUE, 2, "three")
typeof(x)
  • Concrete result: x becomes a character vector because "three" prevents all elements from remaining logical or numeric.

B. Vectors

A vector is a one-dimensional ordered collection and the fundamental data structure on which many R operations are built.

  • Creation: c(4, 7, 9) combines values; 1:5 creates consecutive integers; seq(0, 1, by = 0.25) creates a controlled sequence.
  • Homogeneity: Every element of an atomic vector has the same type.
  • Indexing: x[2] selects position two, x[c(1, 3)] selects multiple positions, and x[-1] excludes position one.
  • Logical selection: x[x > 5] keeps values satisfying the condition x > 5.
  • Named elements: names(x) <- c("a", "b", "c") permits access such as x["b"].
  • Vectorization: Arithmetic is performed element by element.
R
scores <- c(60, 72, 81)
adjusted <- scores + 5
adjusted
  • Concrete result: adjusted is 65, 77, 86; the scalar 5 is recycled across all three elements.
  • Recycling rule: Shorter vectors are repeated during compatible operations, although non-multiple lengths can produce warnings and unreliable results.
  • Useful functions: length(), sum(), mean(), min(), max(), and sort() summarize or transform vectors.

C. Character strings

Character strings represent textual data such as names, labels, categories, and sentences, and R stores them in character vectors.

  • Creation: Text is enclosed in single or double quotation marks, as in "data science" or 'R'.
  • Concatenation: paste("Unit", 12) returns "Unit 12"; paste0("R", "Studio") returns "RStudio" without a separator.
  • Length distinction: length(x) counts vector elements, whereas nchar(x) counts characters within each string.
  • Extraction: substr("analysis", 1, 4) returns "anal" because positions one through four are selected.
  • Case conversion: toupper("R tool") produces "R TOOL", and tolower() converts letters to lowercase.
  • Pattern operations: grepl("data", text) returns logical matches, while sub() replaces the first match and gsub() replaces all matches.
  • Escaping: "\n" represents a newline, "\t" a tab, and \" a literal double quote inside a double-quoted string.
  • Missing versus empty: NA_character_ represents missing text, while "" is a present string containing zero characters.
  • Factors distinction: A factor represents categorical values through defined levels; it is not interchangeable with ordinary free-form character data.

D. Matrices

A matrix is a two-dimensional homogeneous structure arranged in rows and columns.

  • Construction: matrix(data, nrow, ncol) creates a matrix; values fill columns by default.
R
m <- matrix(1:6, nrow = 2, ncol = 3)
m
  • Dimensions: The result has two rows and three columns; dim(m) returns 2 3.
  • Row-wise filling: Adding byrow = TRUE fills one row at a time.
  • Indexing: m[2, 3] selects row two, column three; m[1, ] selects the first row; m[, 2] selects the second column.
  • Naming: rownames(m) and colnames(m) attach meaningful labels.
  • Element-wise arithmetic: m * 2 doubles every entry, while m1 * m2 multiplies corresponding entries.
  • Matrix multiplication: m1 %*% m2 performs algebraic matrix multiplication when inner dimensions agree.
  • Combination: rbind() joins compatible objects by rows, and cbind() joins them by columns.
  • Type rule: Introducing one character value coerces the entire matrix to character storage.

E. Lists

A list is a one-dimensional recursive structure capable of holding objects with different types, lengths, and classes.

  • Construction: list(name = "Asha", scores = c(78, 84), passed = TRUE) stores character, numeric-vector, and logical components together.
  • Named access: student$name retrieves the component named name.
  • Bracket distinction:
    1. student[1] returns a sublist containing the first component.
    2. student[[1]] returns the component itself.
  • Nested objects: A list component can itself be a matrix, data frame, function, model, or another list.
  • Modification: student$age <- 20 adds a component, while student$age <- NULL removes it.
  • Inspection: names(student) reports component names, length(student) counts top-level components, and str(student) displays the nested structure.
  • Practical role: Many modelling functions return lists containing coefficients, fitted values, residuals, and diagnostic information.

F. Dataframe

A data frame is a two-dimensional tabular structure in which columns may have different types but must contain the same number of observations.

  • Construction: data.frame() combines equal-length vectors as columns.
R
students <- data.frame(
  id = c(1, 2, 3),
  name = c("Asha", "Ben", "Chen"),
  score = c(78, 84, 91)
)
  • Structure: Each row represents one student; id, name, and score are variables with three values each.
  • Column types: id and score are numeric, while name is character.
  • Access: students$score selects a column, students[2, ] selects row two, and students[, c("name", "score")] selects named columns.
  • Filtering: students[students$score >= 80, ] keeps rows where the score is at least 80.
  • Adding variables: students$passed <- students$score >= 50 creates a logical column.
  • Dimensions: nrow(), ncol(), and dim() report table size; names() reports column names.
  • Inspection: head() previews initial rows, summary() produces column summaries, and str() reveals types and structure.
  • Difference from matrices: A matrix requires one type throughout, whereas a data frame permits a different type in each column.

IV. Program Design and Execution

An R program organizes expressions into a reproducible sequence: obtain data, validate and transform it, perform analysis, and communicate results. Clear object names, functions, comments, and controlled execution make the sequence maintainable.

A. R programming structure

R programming structure combines sequential statements, conditional decisions, repetition, functions, and explicit handling of data and errors.

  • Sequential execution: A script normally runs from top to bottom, with later statements able to use objects created earlier.
  • Conditional control: if, else if, and else select code according to logical conditions.
R
classify_score <- function(score) {
  if (is.na(score)) {
    return(NA_character_)
  } else if (score >= 50) {
    return("Pass")
  } else {
    return("Fail")
  }
}
  • Function structure: classify_score is the function name, score is its argument, and return() specifies the output.
  • Missing-data guard: is.na(score) is checked first because an unavailable score cannot be safely compared with 50.
  • Iteration: for loops traverse known sequences, while while loops continue as long as a condition remains true.
  • Vectorized preference: scores * 1.1 is usually clearer and faster than looping over every score individually.
  • Function definition: function(arguments) { body } packages reusable logic and creates a local execution environment.
  • Scope: Names created inside a function are normally local; R searches enclosing environments when a name is not found locally.
  • Input and output: Functions such as read.csv() import tabular data, while write.csv() exports results.
  • Error awareness: stop() signals an error, warning() reports a potential problem, and tryCatch() provides controlled error handling.
  • Reproducibility: Fixed scripts, relative project paths, recorded package versions, and set.seed() for random procedures help produce repeatable results.