base-R
Provides base R programming guidance covering data structures, data wrangling, statistical modeling, visualization, and I/O, using only packages included in a standard R installation
Skill files
---name: base-rdescription: Provides base R programming guidance covering data structures, data wrangling, statistical modeling, visualization, and I/O, using only packages included in a standard R installation---# Base R Programming SkillA comprehensive reference for base R programming — covering data structures, control flow, functions, I/O, statistical computing, and plotting.## Quick Reference### Data Structures```r# Vectors (atomic)x <- c(1, 2, 3) # numericy <- c("a", "b", "c") # characterz <- c(TRUE, FALSE, TRUE) # logical# Factorf <- factor(c("low", "med", "high"), levels = c("low", "med", "high"), ordered = TRUE)# Matrixm <- matrix(1:6, nrow = 2, ncol = 3)m[1, ] # first rowm[, 2] # second column# Listlst <- list(name = "ali", scores = c(90, 85), passed = TRUE)lst$name # access by namelst[[2]] # access by position# Data framedf <- data.frame( id = 1:3, name = c("a", "b", "c"), value = c(10.5, 20.3, 30.1), stringsAsFactors = FALSE)df[df$value > 15, ] # filter rowsdf$new_col <- df$value * 2 # add column```### Subsetting```r# Vectorsx[1:3] # by positionx[c(TRUE, FALSE)] # by logicalx[x > 5] # by conditionx[-1] # exclude first# Data framesdf[1:5, ] # first 5 rowsdf[, c("name", "value")] # select columnsdf[df$value > 10, "name"] # filter + selectsubset(df, value > 10, select = c(name, value))# which() for index positionsidx <- which(df$value == max(df$value))```### Control Flow```r# if/elseif (x > 0) { "positive"} else if (x == 0) { "zero"} else { "negative"}# ifelse (vectorized)ifelse(x > 0, "pos", "neg")# for loopfor (i in seq_along(x)) { cat(i, x[i], "\n")}# whilewhile (condition) { # body if (stop_cond) break}# switchswitch(type, "a" = do_a(), "b" = do_b(), stop("Unknown type"))```### Functions```r# Definemy_func <- function(x, y = 1, ...) { result <- x + y return(result) # or just: result}# Anonymous functionssapply(1:5, function(x) x^2)# R 4.1+ shorthand:sapply(1:5, \(x) x^2)# Useful: do.call for calling with a list of argsdo.call(paste, list("a", "b", sep = "-"))```### Apply Family```r# sapply — simplify result to vector/matrixsapply(lst, length)# lapply — always returns listlapply(lst, function(x) x[1])# vapply — like sapply but with type safetyvapply(lst, length, integer(1))# apply — over matrix margins (1=rows, 2=cols)apply(m, 2, sum)# tapply — apply by groupstapply(df$value, df$group, mean)# mapply — multivariatemapply(function(x, y) x + y, 1:3, 4:6)# aggregate — like tapply for data framesaggregate(value ~ group, data = df, FUN = mean)```### String Operations```rpaste("a", "b", sep = "-") # "a-b"paste0("x", 1:3) # "x1" "x2" "x3"sprintf("%.2f%%", 3.14159) # "3.14%"nchar("hello") # 5substr("hello", 1, 3) # "hel"gsub("old", "new", text) # replace allgrep("pattern", x) # indices of matchesgrepl("pattern", x) # logical vectorstrsplit("a,b,c", ",") # list("a","b","c")trimws(" hi ") # "hi"tolower("ABC") # "abc"```### Data I/O```r# CSVdf <- read.csv("data.csv", stringsAsFactors = FALSE)write.csv(df, "output.csv", row.names = FALSE)# Tab-delimiteddf <- read.delim("data.tsv")# Generaldf <- read.table("data.txt", header = TRUE, sep = "\t")# RDS (single R object, preserves types)saveRDS(obj, "data.rds")obj <- readRDS("data.rds")# RData (multiple objects)save(df1, df2, file = "data.RData")load("data.RData")# Connectionscon <- file("big.csv", "r")chunk <- readLines(con, n = 100)close(con)```### Base Plotting```r# Scatterplot(x, y, main = "Title", xlab = "X", ylab = "Y", pch = 19, col = "steelblue", cex = 1.2)# Lineplot(x, y, type = "l", lwd = 2, col = "red")lines(x, y2, col = "blue", lty = 2) # add line# Barbarplot(table(df$category), main = "Counts", col = "lightblue", las = 2)# Histogramhist(x, breaks = 30, col = "grey80", main = "Distribution", xlab = "Value")# Box plotboxplot(value ~ group, data = df, col = "lightyellow", main = "By Group")# Multiple plotspar(mfrow = c(2, 2)) # 2x2 grid# ... four plots ...par(mfrow = c(1, 1)) # reset# Save to filepng("plot.png", width = 800, height = 600)plot(x, y)dev.off()# Add elementslegend("topright", legend = c("A", "B"), col = c("red", "blue"), lty = 1)abline(h = 0, lty = 2, col = "grey")text(x, y, labels = names, pos = 3, cex = 0.8)```### Statistics```r# Descriptivemean(x); median(x); sd(x); var(x)quantile(x, probs = c(0.25, 0.5, 0.75))summary(df)cor(x, y)table(df$category) # frequency table# Linear modelfit <- lm(y ~ x1 + x2, data = df)summary(fit)coef(fit)predict(fit, newdata = new_df)confint(fit)# t-testt.test(x, y) # two-samplet.test(x, mu = 0) # one-samplet.test(before, after, paired = TRUE)# Chi-squarechisq.test(table(df$a, df$b))# ANOVAfit <- aov(value ~ group, data = df)summary(fit)TukeyHSD(fit)# Correlation testcor.test(x, y, method = "pearson")```### Data Manipulation```r# Merge (join)merged <- merge(df1, df2, by = "id") # innermerged <- merge(df1, df2, by = "id", all = TRUE) # full outermerged <- merge(df1, df2, by = "id", all.x = TRUE) # left# Reshapewide <- reshape(long, direction = "wide", idvar = "id", timevar = "time", v.names = "value")long <- reshape(wide, direction = "long", varying = list(c("v1", "v2")), v.names = "value")# Sortdf[order(df$value), ] # ascendingdf[order(-df$value), ] # descendingdf[order(df$group, -df$value), ] # multi-column# Remove duplicatesdf[!duplicated(df), ]df[!duplicated(df$id), ]# Stack / combinerbind(df1, df2) # stack rows (same columns)cbind(df1, df2) # bind columns (same rows)# Transform columnsdf$log_val <- log(df$value)df$category <- cut(df$value, breaks = c(0, 10, 20, Inf), labels = c("low", "med", "high"))```### Environment & Debugging```rls() # list objectsrm(x) # remove objectrm(list = ls()) # clear allstr(obj) # structureclass(obj) # classtypeof(obj) # internal typeis.na(x) # check NAcomplete.cases(df) # rows without NAtraceback() # after errordebug(my_func) # step throughbrowser() # breakpoint in codesystem.time(expr) # timingSys.time() # current time```## Reference FilesFor deeper coverage, read the reference files in `references/`:### Function Gotchas & Quick Reference (condensed from R 4.5.3 Reference Manual)Non-obvious behaviors, surprising defaults, and tricky interactions — only what Claude doesn't already know:- **data-wrangling.md** — Read when: subsetting returns wrong type, apply on data frame gives unexpected coercion, merge/split/cbind behaves oddly, factor levels persist after filtering, table/duplicated edge cases.- **modeling.md** — Read when: formula syntax is confusing (`I()`, `*` vs `:`, `/`), aov gives wrong SS type, glm silently fits OLS, nls won't converge, predict returns wrong scale, optim/optimize needs tuning.- **statistics.md** — Read when: hypothesis test gives surprising result, need to choose correct p.adjust method, clustering parameters seem wrong, distribution function naming is confusing (`d`/`p`/`q`/`r` prefixes).- **visualization.md** — Read when: par settings reset unexpectedly, layout/mfrow interaction is confusing, axis labels are clipped, colors don't look right, need specialty plots (contour, persp, mosaic, pairs).- **io-and-text.md** — Read when: read.table silently drops data or misparses columns, regex behaves differently than expected, sprintf formatting is tricky, write.table output has unwanted row names.- **dates-and-system.md** — Read when: Date/POSIXct conversion gives wrong day, time zones cause off-by-one, difftime units are unexpected, need to find/list/test files programmatically.- **misc-utilities.md** — Read when: do.call behaves differently than direct call, need Reduce/Filter/Map, tryCatch handler doesn't fire, all.equal returns string not logical, time series functions need setup.## Tips for Writing Good R Code- Use `vapply()` over `sapply()` in production code — it enforces return types- Prefer `seq_along(x)` over `1:length(x)` — the latter breaks when `x` is empty- Use `stringsAsFactors = FALSE` in `read.csv()` / `data.frame()` (default changed in R 4.0)- Vectorize operations instead of writing loops when possible- Use `stop()`, `warning()`, `message()` for error handling — not `print()`- `<<-` assigns to parent environment — use sparingly and intentionally- `with(df, expr)` avoids repeating `df$` everywhere- `Sys.setenv()` and `.Renviron` for environment variablesPrompts come from prompts.chat, an open community library dedicated to the public domain (CC0). We refresh our copy every week.