• Descriptive
    • Moments
    • Concentration
    • Central Tendency
    • Variability
    • Stem-and-Leaf Plot
    • Histogram & Frequency Table
    • Data Quality Forensics
    • Conditional EDA
    • Quantiles
    • Kernel Density Estimation
    • Normal QQ Plot
    • Bootstrap Plot

    • Multivariate Descriptive Statistics
  • Distributions
    • Binomial Probabilities
    • Geometric Probabilities
    • Negative Binomial Probabilities
    • Hypergeometric Probabilities
    • Multinomial Probabilities
    • Poisson Probabilities

    • Exponential
    • Gamma
    • Erlang
    • Weibull
    • Rayleigh
    • Lognormal
    • Pareto
    • Inverse Gamma

    • Beta
    • Power
    • Beta Prime (Inv. Beta)
    • Triangular

    • Normal (area)
    • Logistic
    • Laplace
    • Cauchy (standard)
    • Cauchy (location-scale)
    • Gumbel

    • Normal RNG
    • ML Fitting
    • Tukey Lambda PPCC
    • Box-Cox Normality Plot
    • Sample Correlation r

    • Empirical Tests
  • Hypotheses
    • Theoretical Aspects of Hypothesis Testing
    • Bayesian Inference
    • Minimum Sample Size

    • Empirical Tests
    • Multivariate (pair-wise) Testing
  • Models
    • Manual Model Building
  • Time Series
    • Time Series Plot
    • Decomposition
    • Exponential Smoothing

    • Blocked Bootstrap Plot
    • Mean Plot
    • (P)ACF
    • VRM
    • Standard Deviation-Mean Plot
    • Spectral Analysis
    • ARIMA

    • Cross Correlation Function
    • Granger Causality
  1. Appendices
  2. C  R Language Concepts for Statistical Computing
  • Preface
  • Getting Started
    • 1  Introduction
    • 2  Why Do We Need Innovative Technology?
    • 3  Basic Definitions
    • 4  The Big Picture: Why We Analyze Data
  • Introduction to Probability
    • 5  Definitions of Probability
    • 6  Jeffreys’ axiom system
    • 7  Bayes’ Theorem
    • 8  Sensitivity and Specificity
    • 9  Naive Bayes Classifier
    • 10  Law of Large Numbers

    • 11  Problems
  • Probability Distributions
    • 12  Bernoulli Distribution
    • 13  Binomial Distribution
    • 14  Geometric Distribution
    • 15  Negative Binomial Distribution
    • 16  Hypergeometric Distribution
    • 17  Multinomial Distribution
    • 18  Poisson Distribution

    • 19  Uniform Distribution (Rectangular Distribution)
    • 20  Normal Distribution (Gaussian Distribution)
    • 21  Gaussian Naive Bayes Classifier
    • 22  Chi Distribution
    • 23  Chi-squared Distribution (1 parameter)
    • 24  Chi-squared Distribution (2 parameters)
    • 25  Student t-Distribution
    • 26  Fisher F-Distribution
    • 27  Exponential Distribution
    • 28  Lognormal Distribution
    • 29  Gamma Distribution
    • 30  Beta Distribution
    • 31  Weibull Distribution
    • 32  Pareto Distribution
    • 33  Inverse Gamma Distribution
    • 34  Rayleigh Distribution
    • 35  Erlang Distribution
    • 36  Logistic Distribution
    • 37  Laplace Distribution
    • 38  Gumbel Distribution
    • 39  Cauchy Distribution
    • 40  Triangular Distribution
    • 41  Power Distribution
    • 42  Beta Prime Distribution
    • 43  Sample Correlation Distribution

    • 44  Problems
  • Descriptive Statistics & Exploratory Data Analysis
    • 45  Types of Data
    • 46  Datasheets

    • 47  Frequency Plot (Bar Plot)
    • 48  Frequency Table
    • 49  Contingency Table
    • 50  Binomial Classification Metrics
    • 51  Confusion Matrix
    • 52  ROC Analysis

    • 53  Stem-and-Leaf Plot
    • 54  Histogram
    • 55  Data Quality Forensics
    • 56  Quantiles
    • 57  Central Tendency
    • 58  Variability
    • 59  Skewness & Kurtosis
    • 60  Concentration
    • 61  Notched Boxplot
    • 62  Scatterplot
    • 63  Pearson Correlation
    • 64  Rank Correlation
    • 65  Partial Pearson Correlation
    • 66  Simple Linear Regression
    • 67  Moments
    • 68  Quantile-Quantile Plot (QQ Plot)
    • 69  Normal Probability Plot
    • 70  Probability Plot Correlation Coefficient Plot (PPCC Plot)
    • 71  Box-Cox Normality Plot
    • 72  Kernel Density Estimation
    • 73  Bivariate Kernel Density Plot
    • 74  Conditional EDA: Panel Diagnostics
    • 75  Bootstrap Plot (Central Tendency)
    • 76  Survey Scores Rank Order Comparison
    • 77  Cronbach Alpha

    • 78  Equi-distant Time Series
    • 79  Time Series Plot (Run Sequence Plot)
    • 80  Mean Plot
    • 81  Blocked Bootstrap Plot (Central Tendency)
    • 82  Standard Deviation-Mean Plot
    • 83  Variance Reduction Matrix
    • 84  (Partial) Autocorrelation Function
    • 85  Periodogram & Cumulative Periodogram

    • 86  Problems
  • Hypothesis Testing
    • 87  Normal Distributions revisited
    • 88  The Population
    • 89  The Sample
    • 90  The One-Sided Hypothesis Test
    • 91  The Two-Sided Hypothesis Test
    • 92  When to use a one-sided or two-sided test?
    • 93  What if \(\sigma\) is unknown?
    • 94  The Central Limit Theorem (revisited)
    • 95  Statistical Test of the Population Mean with known Variance
    • 96  Statistical Test of the Population Mean with unknown Variance
    • 97  Statistical Test of the Variance
    • 98  Statistical Test of the Population Proportion
    • 99  Statistical Test of the Standard Deviation \(\sigma\)
    • 100  Statistical Test of the difference between Means -- Independent/Unpaired Samples
    • 101  Statistical Test of the difference between Means -- Dependent/Paired Samples
    • 102  Statistical Test of the difference between Variances -- Independent/Unpaired Samples

    • 103  Hypothesis Testing for Research Purposes
    • 104  Decision Thresholds, Alpha, and Confidence Levels
    • 105  Bayesian Inference for Decision-Making
    • 106  One Sample t-Test
    • 107  Skewness & Kurtosis Tests
    • 108  Paired Two Sample t-Test
    • 109  Wilcoxon Signed-Rank Test
    • 110  Unpaired Two Sample t-Test
    • 111  Unpaired Two Sample Welch Test
    • 112  Two One-Sided Tests (TOST) for Equivalence
    • 113  Mann-Whitney U test (Wilcoxon Rank-Sum Test)
    • 114  Bayesian Two Sample Test
    • 115  Median Test based on Notched Boxplots
    • 116  Chi-Squared Tests for Count Data
    • 117  Kolmogorov-Smirnov Test
    • 118  One Way Analysis of Variance (1-way ANOVA)
    • 119  Kruskal-Wallis Test
    • 120  Two Way Analysis of Variance (2-way ANOVA)
    • 121  Repeated Measures ANOVA
    • 122  Friedman Test
    • 123  Testing Correlations
    • 124  A Note on Causality

    • 125  Problems
  • Regression Models
    • 126  Simple Linear Regression Model (SLRM)
    • 127  Multiple Linear Regression Model (MLRM)
    • 128  Logistic Regression
    • 129  Generalized Linear Models
    • 130  Multinomial and Ordinal Logistic Regression
    • 131  Cox Proportional Hazards Regression
    • 132  Conditional Inference Trees
    • 133  Leaf Diagnostics for Conditional Inference Trees
    • 134  Hypothesis Testing with Linear Regression Models (from a Practical Point of View)

    • 135  Problems
  • Introduction to Time Series Analysis
    • 136  Case: the Market of Health and Personal Care Products
    • 137  Decomposition of Time Series
    • 138  Ad hoc Forecasting of Time Series
  • Box-Jenkins Analysis
    • 139  Introduction to Box-Jenkins Analysis
    • 140  Theoretical Concepts
    • 141  Stationarity
    • 142  Identifying ARMA parameters
    • 143  Estimating ARMA Parameters and Residual Diagnostics
    • 144  Forecasting with ARIMA models
    • 145  Intervention Analysis
    • 146  Cross-Correlation Function
    • 147  Transfer Function Noise Models
    • 148  General-to-Specific Modeling
  • References
  • Appendices
    • Appendices
    • A  Method Selection Guide
    • B  Presentations and Teaching Materials
    • C  R Language Concepts for Statistical Computing
    • D  Matrix Algebra
    • E  Standard Normal Table (Gaussian Table)
    • F  Critical values of Student’s \(t\) distribution with \(\nu\) degrees of freedom
    • G  Upper-tail critical values of the \(\chi^2\)-distribution with \(\nu\) degrees of freedom
    • H  Lower-tail critical values of the \(\chi^2\)-distribution with \(\nu\) degrees of freedom

Table of contents

  • C.1 1. Computational Model of R
  • C.2 2. Objects and Data Structures
    • C.2.1 2.1 Atomic vectors
    • C.2.2 2.2 Factors
    • C.2.3 2.3 Lists
    • C.2.4 2.4 Matrices and arrays
    • C.2.5 2.5 Data frames and tibbles
  • C.3 3. Operators and Evaluation
  • C.4 4. Missingness and Special Numeric Values
  • C.5 5. Coercion and Type Discipline
  • C.6 6. Indexing and Subsetting
  • C.7 7. Functions, Scope, and Environments
  • C.8 8. Control Flow and Vectorization
  • C.9 9. Formula Interface in Statistical Models
  • C.10 10. Packages, Documentation, and Citation
  • C.11 11. Practical Guidance for Students
DRAFT This draft is under development — DO NOT CITE OR SHARE.
  1. Appendices
  2. C  R Language Concepts for Statistical Computing

Appendix C — R Language Concepts for Statistical Computing

This appendix provides a structured overview of core R language concepts for readers who want to move beyond app-based usage and perform analysis directly in code. The focus is on concepts that are repeatedly used in statistical workflows.

C.1 1. Computational Model of R

R is an interpreted language with vectorized semantics and a functional core. Most statistical procedures in R are exposed as functions that operate on vectors, matrices, data frames, or model objects. In practice, this means:

  • Objects are first-class values that can be created, transformed, and passed to functions.
  • Functions are the central abstraction for analysis and automation.
  • Many operations are defined element-wise, which reduces the need for explicit loops.

R can be used procedurally, functionally, and object-orientedly (e.g., S3 classes in many statistical packages).

C.2 2. Objects and Data Structures

C.2.1 2.1 Atomic vectors

An atomic vector stores values of a single underlying type (logical, integer, double, character, etc.).

Code
x_num <- c(2.1, 3.4, 5.0)
x_chr <- c("A", "B", "C")
typeof(x_num)
length(x_num)

C.2.2 2.2 Factors

Factors represent categorical variables with explicit levels. Many model-fitting functions automatically encode factors as contrast matrices (treatment/dummy coding by default; see contrasts() for alternatives).

Code
g <- factor(c("control", "treatment", "control"))
levels(g)

C.2.3 2.3 Lists

Lists can store heterogeneous elements and are widely used for function returns.

Code
obj <- list(a = 1:3, b = "text", c = TRUE)
obj$a

C.2.4 2.4 Matrices and arrays

Matrices are 2-dimensional homogeneous structures. Arrays generalize this to higher dimensions.

Code
M <- matrix(1:9, nrow = 3)
dim(M)

C.2.5 2.5 Data frames and tibbles

A data frame is a tabular structure with rows as observations and columns as variables. Columns can have different types. Tibbles are modern data frames with stricter printing and subsetting behavior.

Code
df <- data.frame(y = c(1.2, 2.3), group = factor(c("A", "B")))
str(df)

C.3 3. Operators and Evaluation

R distinguishes assignment from comparison:

  • Assignment: <-, = (= also names function arguments, e.g., na.rm = TRUE; prefer <- for variable assignment to avoid ambiguity)
  • Equality test: ==
  • Relational operators: <, <=, >, >=, !=
  • Vectorized logical operators: !, &, | (element-wise; use in subsetting and ifelse())
  • Scalar short-circuit operators: &&, || (first element only; use in if() control flow)
  • Membership: %in%

Operator precedence matters in complex expressions. Parentheses should be used explicitly when readability is important.

Code
x <- 5
y <- 2
x == y
(x > 1) & (y < 3)

C.4 4. Missingness and Special Numeric Values

R distinguishes several special values:

  • NA: missing value
  • NaN: undefined numeric result (e.g., 0/0)
  • Inf, -Inf: positive/negative infinity

Most summary functions propagate NA unless na.rm = TRUE is set.

Code
z <- c(4, NA, 7, 10)
mean(z)                 # returns NA
mean(z, na.rm = TRUE)   # ignores missing values
is.na(z)

C.5 5. Coercion and Type Discipline

R may coerce types implicitly. This is convenient but can introduce subtle errors if not monitored.

Code
c(1, 2, "3")      # numeric values coerced to character
as.numeric("3.14")
as.factor(c("low", "high", "low"))

In statistical work, type checks (str, typeof, is.factor, is.numeric) should be part of routine data validation.

C.6 6. Indexing and Subsetting

Subsetting can be positional, logical, or name-based.

Code
x <- c(10, 20, 30, 40)
x[2]                  # positional
x[x > 20]             # logical

df <- data.frame(a = 1:4, b = c("x", "y", "x", "z"))
df[df$a >= 3, "b"]    # row/column subset

For matrices/data frames, be explicit about dimensions (drop = FALSE) when a 2D structure must be preserved.

C.7 7. Functions, Scope, and Environments

Functions encapsulate logic and improve reproducibility. R uses lexical scoping: a function resolves names in its local environment first, then in enclosing environments.

Code
compute_mean <- function(x, na_rm = TRUE) {
  mean(x, na.rm = na_rm)
}
compute_mean(c(1, 2, NA, 4))

As a rule, functions should avoid side effects (e.g., modifying global objects) unless explicitly intended.

C.8 8. Control Flow and Vectorization

R supports if, for, while, and repeat, but vectorized solutions are often clearer and faster for statistical tasks.

Code
x <- 1:10
ifelse(x %% 2 == 0, "even", "odd")

The apply family (apply, lapply, sapply, vapply) is frequently used for structured iteration.

C.9 9. Formula Interface in Statistical Models

Many methods in R use the formula interface:

  • y ~ x1 + x2: additive model
  • y ~ x1 * x2: interaction plus main effects
  • y ~ .: all available predictors
  • y ~ x - 1: no intercept
Code
fit <- lm(mpg ~ wt + hp, data = mtcars)
summary(fit)

Model outputs are structured objects; extraction of coefficients, residuals, fitted values, and diagnostics is typically done with accessor functions.

C.10 10. Packages, Documentation, and Citation

R’s statistical ecosystem is package-based. A robust workflow includes:

  1. Install once (install.packages)
  2. Load per session (library)
  3. Verify behavior via help pages and examples
  4. Cite packages used in academic work
Code
install.packages("lmtest")
library(lmtest)
?bptest
citation("lmtest")

C.11 11. Practical Guidance for Students

When moving from app-based analysis to coding, prioritize the following sequence:

  1. Data structures (vector, factor, data.frame)
  2. Missing data handling (NA, na.rm, complete.cases)
  3. Formula syntax for models
  4. Function writing for repeatable workflows

This sequence is sufficient to reproduce most analyses presented in this handbook with R.

B  Presentations and Teaching Materials
D  Matrix Algebra

© 2026 Patrick Wessa. Provided as-is, without warranty.

Feedback: e-mail | Anonymous contributions: click to copy (Sats) | click to copy (XMR)

Cookie Preferences