1
---
2
name: base-r
3
description: 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
4
---
5
6
# Base R Programming Skill
7
8
A comprehensive reference for base R programming — covering data structures, control flow, functions, I/O, statistical computing, and plotting.
9
10
## Quick Reference
11
12
### Data Structures
13
14
```r
15
# Vectors (atomic)
16
x <- c(1, 2, 3) # numeric
17
y <- c("a", "b", "c") # character
18
z <- c(TRUE, FALSE, TRUE) # logical
19
20
# Factor
21
f <- factor(c("low", "med", "high"), levels = c("low", "med", "high"), ordered = TRUE)
22
23
# Matrix
24
m <- matrix(1:6, nrow = 2, ncol = 3)
25
m[1, ] # first row
26
m[, 2] # second column
27
28
# List
29
lst <- list(name = "ali", scores = c(90, 85), passed = TRUE)
30
lst$name # access by name
31
lst[[2]] # access by position
32
33
# Data frame
34
df <- data.frame(
35
id = 1:3,
36
name = c("a", "b", "c"),
37
value = c(10.5, 20.3, 30.1),
38
stringsAsFactors = FALSE
39
)
40
df[df$value > 15, ] # filter rows
41
df$new_col <- df$value * 2 # add column
42
```
43
44
### Subsetting
45
46
```r
47
# Vectors
48
x[1:3] # by position
49
x[c(TRUE, FALSE)] # by logical
50
x[x > 5] # by condition
51
x[-1] # exclude first
52
53
# Data frames
54
df[1:5, ] # first 5 rows
55
df[, c("name", "value")] # select columns
56
df[df$value > 10, "name"] # filter + select
57
subset(df, value > 10, select = c(name, value))
58
59
# which() for index positions
60
idx <- which(df$value == max(df$value))
61
```
62
63
### Control Flow
64
65
```r
66
# if/else
67
if (x > 0) {
68
"positive"
69
} else if (x == 0) {
70
"zero"
71
} else {
72
"negative"
73
}
74
75
# ifelse (vectorized)
76
ifelse(x > 0, "pos", "neg")
77
78
# for loop
79
for (i in seq_along(x)) {
80
cat(i, x[i], "\n")
81
}
82
83
# while
84
while (condition) {
85
# body
86
if (stop_cond) break
87
}
88
89
# switch
90
switch(type,
91
"a" = do_a(),
92
"b" = do_b(),
93
stop("Unknown type")
94
)
95
```
96
97
### Functions
98
99
```r
100
# Define
101
my_func <- function(x, y = 1, ...) {
102
result <- x + y
103
return(result) # or just: result
104
}
105
106
# Anonymous functions
107
sapply(1:5, function(x) x^2)
108
# R 4.1+ shorthand:
109
sapply(1:5, \(x) x^2)
110
111
# Useful: do.call for calling with a list of args
112
do.call(paste, list("a", "b", sep = "-"))
113
```
114
115
### Apply Family
116
117
```r
118
# sapply — simplify result to vector/matrix
119
sapply(lst, length)
120
121
# lapply — always returns list
122
lapply(lst, function(x) x[1])
123
124
# vapply — like sapply but with type safety
125
vapply(lst, length, integer(1))
126
127
# apply — over matrix margins (1=rows, 2=cols)
128
apply(m, 2, sum)
129
130
# tapply — apply by groups
131
tapply(df$value, df$group, mean)
132
133
# mapply — multivariate
134
mapply(function(x, y) x + y, 1:3, 4:6)
135
136
# aggregate — like tapply for data frames
137
aggregate(value ~ group, data = df, FUN = mean)
138
```
139
140
### String Operations
141
142
```r
143
paste("a", "b", sep = "-") # "a-b"
144
paste0("x", 1:3) # "x1" "x2" "x3"
145
sprintf("%.2f%%", 3.14159) # "3.14%"
146
nchar("hello") # 5
147
substr("hello", 1, 3) # "hel"
148
gsub("old", "new", text) # replace all
149
grep("pattern", x) # indices of matches
150
grepl("pattern", x) # logical vector
151
strsplit("a,b,c", ",") # list("a","b","c")
152
trimws(" hi ") # "hi"
153
tolower("ABC") # "abc"
154
```
155
156
### Data I/O
157
158
```r
159
# CSV
160
df <- read.csv("data.csv", stringsAsFactors = FALSE)
161
write.csv(df, "output.csv", row.names = FALSE)
162
163
# Tab-delimited
164
df <- read.delim("data.tsv")
165
166
# General
167
df <- read.table("data.txt", header = TRUE, sep = "\t")
168
169
# RDS (single R object, preserves types)
170
saveRDS(obj, "data.rds")
171
obj <- readRDS("data.rds")
172
173
# RData (multiple objects)
174
save(df1, df2, file = "data.RData")
175
load("data.RData")
176
177
# Connections
178
con <- file("big.csv", "r")
179
chunk <- readLines(con, n = 100)
180
close(con)
181
```
182
183
### Base Plotting
184
185
```r
186
# Scatter
187
plot(x, y, main = "Title", xlab = "X", ylab = "Y",
188
pch = 19, col = "steelblue", cex = 1.2)
189
190
# Line
191
plot(x, y, type = "l", lwd = 2, col = "red")
192
lines(x, y2, col = "blue", lty = 2) # add line
193
194
# Bar
195
barplot(table(df$category), main = "Counts",
196
col = "lightblue", las = 2)
197
198
# Histogram
199
hist(x, breaks = 30, col = "grey80",
200
main = "Distribution", xlab = "Value")
201
202
# Box plot
203
boxplot(value ~ group, data = df,
204
col = "lightyellow", main = "By Group")
205
206
# Multiple plots
207
par(mfrow = c(2, 2)) # 2x2 grid
208
# ... four plots ...
209
par(mfrow = c(1, 1)) # reset
210
211
# Save to file
212
png("plot.png", width = 800, height = 600)
213
plot(x, y)
214
dev.off()
215
216
# Add elements
217
legend("topright", legend = c("A", "B"),
218
col = c("red", "blue"), lty = 1)
219
abline(h = 0, lty = 2, col = "grey")
220
text(x, y, labels = names, pos = 3, cex = 0.8)
221
```
222
223
### Statistics
224
225
```r
226
# Descriptive
227
mean(x); median(x); sd(x); var(x)
228
quantile(x, probs = c(0.25, 0.5, 0.75))
229
summary(df)
230
cor(x, y)
231
table(df$category) # frequency table
232
233
# Linear model
234
fit <- lm(y ~ x1 + x2, data = df)
235
summary(fit)
236
coef(fit)
237
predict(fit, newdata = new_df)
238
confint(fit)
239
240
# t-test
241
t.test(x, y) # two-sample
242
t.test(x, mu = 0) # one-sample
243
t.test(before, after, paired = TRUE)
244
245
# Chi-square
246
chisq.test(table(df$a, df$b))
247
248
# ANOVA
249
fit <- aov(value ~ group, data = df)
250
summary(fit)
251
TukeyHSD(fit)
252
253
# Correlation test
254
cor.test(x, y, method = "pearson")
255
```
256
257
### Data Manipulation
258
259
```r
260
# Merge (join)
261
merged <- merge(df1, df2, by = "id") # inner
262
merged <- merge(df1, df2, by = "id", all = TRUE) # full outer
263
merged <- merge(df1, df2, by = "id", all.x = TRUE) # left
264
265
# Reshape
266
wide <- reshape(long, direction = "wide",
267
idvar = "id", timevar = "time", v.names = "value")
268
long <- reshape(wide, direction = "long",
269
varying = list(c("v1", "v2")), v.names = "value")
270
271
# Sort
272
df[order(df$value), ] # ascending
273
df[order(-df$value), ] # descending
274
df[order(df$group, -df$value), ] # multi-column
275
276
# Remove duplicates
277
df[!duplicated(df), ]
278
df[!duplicated(df$id), ]
279
280
# Stack / combine
281
rbind(df1, df2) # stack rows (same columns)
282
cbind(df1, df2) # bind columns (same rows)
283
284
# Transform columns
285
df$log_val <- log(df$value)
286
df$category <- cut(df$value, breaks = c(0, 10, 20, Inf),
287
labels = c("low", "med", "high"))
288
```
289
290
### Environment & Debugging
291
292
```r
293
ls() # list objects
294
rm(x) # remove object
295
rm(list = ls()) # clear all
296
str(obj) # structure
297
class(obj) # class
298
typeof(obj) # internal type
299
is.na(x) # check NA
300
complete.cases(df) # rows without NA
301
traceback() # after error
302
debug(my_func) # step through
303
browser() # breakpoint in code
304
system.time(expr) # timing
305
Sys.time() # current time
306
```
307
308
## Reference Files
309
310
For deeper coverage, read the reference files in `references/`:
311
312
### Function Gotchas & Quick Reference (condensed from R 4.5.3 Reference Manual)
313
Non-obvious behaviors, surprising defaults, and tricky interactions — only what Claude doesn't already know:
314
- **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.
315
- **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.
316
- **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).
317
- **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).
318
- **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.
319
- **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.
320
- **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.
321
322
## Tips for Writing Good R Code
323
324
- Use `vapply()` over `sapply()` in production code — it enforces return types
325
- Prefer `seq_along(x)` over `1:length(x)` — the latter breaks when `x` is empty
326
- Use `stringsAsFactors = FALSE` in `read.csv()` / `data.frame()` (default changed in R 4.0)
327
- Vectorize operations instead of writing loops when possible
328
- Use `stop()`, `warning()`, `message()` for error handling — not `print()`
329
- `<<-` assigns to parent environment — use sparingly and intentionally
330
- `with(df, expr)` avoids repeating `df$` everywhere
331
- `Sys.setenv()` and `.Renviron` for environment variables
332