Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

📊 Chapter 29 — R Programming Language

Complete reference for R — base functions, dplyr, ggplot2, and statistical computing with copy-paste examples.
Part of The Direct Path to Linux Ubuntu — free for all.

4Packages
124+Functions
5Examples
RscriptRun command
R 4.4Version
FreeNo login
🔢 Base R 🔧 Data Wrangling 📈 Visualization 🧮 Statistics ⚡ Examples

🔢 Base R

🔢 base RBuilt-in vectors, data frames, and functions

🔧 Data Wrangling

🔧 dplyrData manipulation — filter, select, mutate, summarise

📈 Visualization

📈 ggplot2Data visualization — grammar of graphics

🧮 Statistics

🧮 statsStatistical tests, linear models, and distributions

⚡ Quick Examples

Save as .R file and run with Rscript script.R.

Hello, R!

R basics — vectors, functions, and control flow.

cat("R version:", R.version$major, ".", R.version$minor, "\n", sep="")
cat("Hello, MyWebUniversity!\n")
x <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)
cat("Vector:", x, "\n")
cat("Mean:", mean(x), " SD:", round(sd(x),3), "\n")
cat("Unique sorted:", sort(unique(x)), "\n")
fibonacci <- function(n) {
  if (n <= 0) return(integer(0))
  if (n == 1) return(0L)
  fib <- integer(n); fib[1] <- 0L; if(n>1) fib[2] <- 1L
  for (i in seq_len(max(0,n-2))+2) fib[i] <- fib[i-1] + fib[i-2]
  fib
}
cat("Fibonacci(10):", fibonacci(10), "\n")
is_prime <- function(n) if(n<2) FALSE else all(n %% 2:max(2,floor(sqrt(n))) != 0)
cat("Primes 1-20:", Filter(is_prime, 1:20), "\n")
# Rscript hello.R

Data Analysis Pipeline

Load, clean, and analyze data with dplyr.

library(dplyr)
set.seed(123)
n  <- 200
df <- data.frame(
  student_id = 1:n,
  subject    = sample(c("Math","Science","English","History"), n, replace=TRUE),
  score      = pmax(0, pmin(100, round(rnorm(n, 75, 15)))),
  year       = sample(2023:2026, n, replace=TRUE)
)
cat("=== Overview ===\n")
cat("Rows:", nrow(df), " Cols:", ncol(df), "\n")
print(head(df, 3))

cat("\n=== Score by Subject ===\n")
df |>
  group_by(subject) |>
  summarise(n=n(), avg=round(mean(score),1), med=median(score),
            pass_rate=paste0(round(100*mean(score>=60),1),"%")) |>
  arrange(desc(avg)) |>
  print()

cat("\n=== Top 5 students ===\n")
df |> slice_max(score, n=5) |> select(student_id, subject, score) |> print()
# Rscript pipeline.R  (install.packages("dplyr"))

Statistical Tests

t-test, ANOVA, correlation, and linear regression.

set.seed(42)
A <- rnorm(30, mean=78, sd=8)
B <- rnorm(30, mean=84, sd=9)
C <- rnorm(30, mean=82, sd=7)

cat("=== One-way ANOVA ===\n")
scores  <- c(A, B, C)
methods <- rep(c("A","B","C"), each=30)
print(summary(aov(scores ~ methods)))

cat("=== Pairwise T-Tests ===\n")
pw <- pairwise.t.test(scores, methods, p.adjust.method="bonferroni")
print(round(pw$p.value, 4))

cat("\n=== Pearson Correlation ===\n")
hours <- runif(50, 1, 10)
exam  <- 50 + 4*hours + rnorm(50, 0, 5)
ct    <- cor.test(hours, exam)
cat(sprintf("r=%.4f  p=%.6f  95%% CI: [%.4f, %.4f]\n",
    ct$estimate, ct$p.value, ct$conf.int[1], ct$conf.int[2]))

cat("\n=== Linear Model ===\n")
mdl <- lm(exam ~ hours)
cat("Intercept:", round(coef(mdl)[1],3), "\n")
cat("Slope:    ", round(coef(mdl)[2],3), "\n")
cat("R²:       ", round(summary(mdl)$r.squared,4), "\n")
# Rscript tests.R

Machine Learning with caret

Train and evaluate a classification model.

library(caret)
data(iris)
cat("Dataset: iris  Rows:", nrow(iris), " Species:", levels(iris$Species), "\n")

set.seed(2026)
idx   <- createDataPartition(iris$Species, p=0.8, list=FALSE)
train <- iris[idx, ]; test <- iris[-idx, ]

ctrl  <- trainControl(method="cv", number=5, verboseIter=FALSE)
model <- train(Species ~ ., data=train, method="rf", trControl=ctrl, ntree=100)

cat("\n=== Cross-Validation Results ===\n")
print(model$results[, c("mtry","Accuracy","Kappa")])

preds <- predict(model, test)
cm    <- confusionMatrix(preds, test$Species)
cat("\n=== Confusion Matrix ===\n"); print(cm$table)
cat("\nAccuracy:", round(cm$overall["Accuracy"],4), "\n")
cat("Kappa:   ", round(cm$overall["Kappa"],4), "\n")

cat("\n=== Variable Importance ===\n")
vi <- varImp(model)$importance; vi$Feature <- rownames(vi)
print(vi[order(-vi$Overall),])
# Rscript ml_demo.R  (install.packages(c("caret","randomForest")))

Shiny Web App Preview

Interactive data visualization with R Shiny.

# Save as app.R and run with: shiny::runApp()
# install.packages("shiny")
library(shiny)
library(ggplot2)

ui <- fluidPage(
  titlePanel("MyWebUniversity — Score Explorer"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Number of bins:", min=5, max=50, value=20),
      selectInput("subject", "Subject:", choices=c("Math","Science","All")),
      checkboxInput("show_density", "Show density curve", TRUE),
      checkboxInput("show_mean",    "Show mean line",     TRUE)
    ),
    mainPanel(
      plotOutput("histogram", height="400px"),
      verbatimTextOutput("stats")
    )
  )
)

server <- function(input, output) {
  data_r <- reactive({
    set.seed(42)
    df <- data.frame(
      score   = c(rnorm(100,78,10), rnorm(100,82,12)),
      subject = rep(c("Math","Science"), each=100))
    if (input$subject != "All") df <- df[df$subject==input$subject,]
    df
  })

  output$histogram <- renderPlot({
    p <- ggplot(data_r(), aes(score)) +
      geom_histogram(aes(y=after_stat(density)), bins=input$bins,
                     fill="steelblue", alpha=0.7, color="white")
    if (input$show_density) p <- p + geom_density(color="red", linewidth=1)
    if (input$show_mean)    p <- p + geom_vline(xintercept=mean(data_r()$score),
                                                  color="orange", linetype="dashed")
    p + labs(title=paste("Distribution —", input$subject)) + theme_minimal()
  })
  output$stats <- renderPrint({ summary(data_r()$score) })
}

shiny::runApp(list(ui=ui, server=server))
# Open http://localhost:PORT in your browser