R is vector-based — nearly all operations work element-wise on vectors without explicit loops. The data.frame is R's core data structure for tabular data.
Load: library(base R) (base R auto-loaded)
| Function | Signature | Description |
|---|---|---|
| c() | c(...) → vector | Combine values into a vector |
| length() | length(x) → integer | Number of elements |
| seq() | seq(from, to, by) → vector | Generate sequence |
| rep() | rep(x, times) → vector | Repeat elements |
| vector ops | x + y, x * y, x^2 | Vectorized arithmetic (element-wise) |
| sum/prod | sum(x) / prod(x) → numeric | Sum / product of all elements |
| mean/median | mean(x) / median(x) → numeric | Arithmetic mean / median |
| sd/var | sd(x) / var(x) → numeric | Standard deviation / variance |
| min/max | min(x) / max(x) → numeric | Minimum / maximum |
| range() | range(x) → c(min, max) | Return min and max |
| which() | which(logical_vec) → integer indices | Indices where condition is TRUE |
| any/all | any(x) / all(x) → logical | Any / all TRUE |
| sort() | sort(x, decreasing=FALSE) → vector | Sort vector |
| order() | order(x) → integer indices | Indices that would sort x |
| rev() | rev(x) → vector | Reverse vector |
| unique() | unique(x) → vector | Remove duplicate elements |
| table() | table(x) → table | Frequency table of values |
| paste() | paste(..., sep=' ') → string | Concatenate strings |
| paste0() | paste0(...) → string | Concatenate strings (no separator) |
| sprintf() | sprintf(fmt, ...) → string | Formatted strings |
| nchar() | nchar(x) → integer | String length |
| toupper/tolower | toupper(x) / tolower(x) | Case conversion |
| gsub() | gsub(pattern, replacement, x) | Replace all regex matches |
| grep() | grep(pattern, x) → indices | Return indices of matching elements |
| grepl() | grepl(pattern, x) → logical | Return TRUE/FALSE for each match |
| strsplit() | strsplit(x, split) → list | Split string by pattern |
| data.frame() | data.frame(...) → data.frame | Create tabular data structure |
| nrow/ncol | nrow(df) / ncol(df) → integer | Number of rows / columns |
| dim() | dim(df) → c(nrow, ncol) | Dimensions of data frame |
| head/tail | head(df, n=6) / tail(df, n=6) | First/last n rows |
| str() | str(obj) | Compact structure display |
| summary() | summary(obj) | Statistical summary |
| names() | names(x) → character | Get/set names of object |
| df$col | df$column_name | Access data frame column |
| df[row, col] | df[1:5, c('a','b')] | Subset by row/column |
| subset() | subset(df, condition, select=cols) | Filter rows and select columns |
| merge() | merge(x, y, by='key') | SQL-like join of two data frames |
| apply() | apply(matrix, 1or2, FUN) | Apply function over rows(1) or cols(2) |
| sapply() | sapply(x, FUN) → vector/matrix | Apply over list, simplify result |
| lapply() | lapply(x, FUN) → list | Apply over list, return list |
| tapply() | tapply(x, INDEX, FUN) | Apply function by group |
| which.min/max | which.min(x) / which.max(x) | Index of min/max value |
| cumsum/cumprod | cumsum(x) / cumprod(x) | Cumulative sum / product |
| diff() | diff(x, lag=1) | Lagged differences |
| cut() | cut(x, breaks=5) | Divide range into intervals |
| Reduce() | Reduce(f, x) | Left fold over vector |
| Filter() | Filter(f, x) | Keep elements where f() is TRUE |
| Map() | Map(f, ...) | Apply f to corresponding elements |
Run with Rscript script.R.
# R fundamentals — vectors and data frames
x <- c(4, 7, 2, 9, 1, 5, 8, 3, 6)
cat("Vector:", x, "\n")
cat("Mean:", mean(x), " SD:", round(sd(x), 3), "\n")
cat("Sorted:", sort(x), "\n")
cat("Above mean:", x[x > mean(x)], "\n")
# Vectorized operations (no loops needed!)
n <- 1:10
cat("Squares:", n^2, "\n")
cat("Even squares:", (n^2)[n %% 2 == 0], "\n")
cat("Cumulative sum:", cumsum(n), "\n")
# String operations
langs <- c("Python", "R", "Julia", "Go", "Rust")
cat("Upper:", toupper(langs), "\n")
cat("Long names:", langs[nchar(langs) > 2], "\n")
cat("Contains 'o':", langs[grepl("o", langs, ignore.case=TRUE)], "\n")
# Data frame
students <- data.frame(
Name = c("Alice","Bob","Carol","Dave","Eve"),
Subject = c("Math","Science","Math","Science","Math"),
Score = c(95, 87, 92, 78, 98),
stringsAsFactors = FALSE
)
cat("\n=== Data Frame ===\n"); print(students)
cat("\nSummary:\n"); print(summary(students$Score))
# Subset
top <- subset(students, Score >= 90, select = c(Name, Score))
cat("\nTop scorers:\n"); print(top)
# tapply: mean score by subject
avg_by_subject <- tapply(students$Score, students$Subject, mean)
cat("\nAverage by subject:\n"); print(avg_by_subject)
# Rscript base_demo.R