Unit 12: R Tool
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, andSCOREare three different names. - One-based indexing: The first element of an object has position
1, not position0.
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 + 3returns5. - Assignment: The operator
<-conventionally stores a value under a name.
radius <- 4
area <- pi * radius^2
area- Named objects: Here,
radiusstores4,piis R’s built-in constant, andareastores the calculated circle area. - Functions: Operations are commonly expressed as function calls such as
mean(x), wherexis the supplied data object. - Comments: Text following
#is ignored during execution and documents the program. - Help system:
?meanopens documentation formean(), whilehelp.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, andls()lists objects in memory. - Missing values:
NArepresents an unavailable value; calculations may require an option such asmean(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
.Rextension; 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)orhist(x). - Packages pane: Lists installed packages and allows them to be attached or detached.
- Help pane: Presents R documentation within the IDE.
- Projects: An
.Rprojproject associates scripts, data, and output with a particular working directory, making analyses easier to organize and reproduce. - Script-based workflow:
- Write commands in a script rather than relying only on console history.
- Run and inspect small sections during development.
- 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, andstr(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.
x <- c(TRUE, 2, "three")
typeof(x)- Concrete result:
xbecomes 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:5creates 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, andx[-1]excludes position one. - Logical selection:
x[x > 5]keeps values satisfying the conditionx > 5. - Named elements:
names(x) <- c("a", "b", "c")permits access such asx["b"]. - Vectorization: Arithmetic is performed element by element.
scores <- c(60, 72, 81)
adjusted <- scores + 5
adjusted- Concrete result:
adjustedis65, 77, 86; the scalar5is 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(), andsort()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, whereasnchar(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", andtolower()converts letters to lowercase. - Pattern operations:
grepl("data", text)returns logical matches, whilesub()replaces the first match andgsub()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.
m <- matrix(1:6, nrow = 2, ncol = 3)
m- Dimensions: The result has two rows and three columns;
dim(m)returns2 3. - Row-wise filling: Adding
byrow = TRUEfills 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)andcolnames(m)attach meaningful labels. - Element-wise arithmetic:
m * 2doubles every entry, whilem1 * m2multiplies corresponding entries. - Matrix multiplication:
m1 %*% m2performs algebraic matrix multiplication when inner dimensions agree. - Combination:
rbind()joins compatible objects by rows, andcbind()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$nameretrieves the component namedname. - Bracket distinction:
student[1]returns a sublist containing the first component.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 <- 20adds a component, whilestudent$age <- NULLremoves it. - Inspection:
names(student)reports component names,length(student)counts top-level components, andstr(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.
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, andscoreare variables with three values each. - Column types:
idandscoreare numeric, whilenameis character. - Access:
students$scoreselects a column,students[2, ]selects row two, andstudents[, c("name", "score")]selects named columns. - Filtering:
students[students$score >= 80, ]keeps rows where the score is at least80. - Adding variables:
students$passed <- students$score >= 50creates a logical column. - Dimensions:
nrow(),ncol(), anddim()report table size;names()reports column names. - Inspection:
head()previews initial rows,summary()produces column summaries, andstr()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, andelseselect code according to logical conditions.
classify_score <- function(score) {
if (is.na(score)) {
return(NA_character_)
} else if (score >= 50) {
return("Pass")
} else {
return("Fail")
}
}- Function structure:
classify_scoreis the function name,scoreis its argument, andreturn()specifies the output. - Missing-data guard:
is.na(score)is checked first because an unavailable score cannot be safely compared with50. - Iteration:
forloops traverse known sequences, whilewhileloops continue as long as a condition remains true. - Vectorized preference:
scores * 1.1is 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, whilewrite.csv()exports results. - Error awareness:
stop()signals an error,warning()reports a potential problem, andtryCatch()provides controlled error handling. - Reproducibility: Fixed scripts, relative project paths, recorded package versions, and
set.seed()for random procedures help produce repeatable results.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →