# R Cheat Sheet: Vectors, Data Frames, Strings and Files

Source: https://srvscripts.com/guides/r-cheat-sheet/
Updated: 2026-10-09
Publisher: srvScripts (https://srvscripts.com/)

**Short answer:** In R, everything is a vector: `c(3, 1, 2)` builds one, operations apply element by element, and indexes start at 1. Assign with `<-`, subset with `x[x > 1]` or `df[df$cpu > 50, ]`, loop less and use `sapply`, `vapply` or `Map` instead, chain steps with the native pipe `|>`, and write short functions as `\(x) x + 1`. Read data with `read.csv()`, catch errors with `tryCatch()`, and summarise with `summary()`, `table()` and `aggregate()`.

The examples in this R cheat sheet were run with R 4.3.3 on 9 October 2026, using base R only. The current release is R 4.6.1; functions marked 4.4+ or later were checked against the R NEWS file.

## Vectors and basic types

| Syntax | What it does | Example |
| --- | --- | --- |
| x  1, "big", "small") |
| is.na(), as.integer(), as.character() | Test and convert | as.numeric("abc") gives NA with a warning |
| factor(x, levels = …) | Categorical data with fixed levels | table(f) counts per level |
| matrix(1:6, nrow = 2) | Matrix (filled by column); %*% multiplies | m[2, 3] |

Never compare floating-point numbers with `==`: `0.1 + 0.2 == 0.3` is `FALSE`. Use `isTRUE(all.equal(a, b))`.

## Indexing and subsetting

| Syntax | Returns | Example |
| --- | --- | --- |
| x[2], x[c(1, 3)] | Elements by position (1-based) | x[length(x)] is the last |
| x[-1] | Everything except position 1 | x[-(1:2)] |
| x[x > 1] | Elements where a logical test is TRUE | lat[lat > 500] |
| v["b"] | By name | v  50, c("host", "cpu")] |
| head(x, n), tail(x, n) | First or last n | head(df, 3) |

## Data frames

| Function | What it does | Example |
| --- | --- | --- |
| data.frame() | Build a table from equal-length vectors | data.frame(host = c("web01", "db01"), cpu = c(35, 55)) |
| str(df), summary(df) | Structure and per-column summaries | First thing to run on new data |
| nrow, ncol, names | Size and column names | names(df) |
| df$new  50, select = c(host, cpu)) |
| aggregate(y ~ g, data, FUN) | Group and summarise | aggregate(cpu ~ role, data = df, FUN = mean) |
| tapply(x, g, f) | Apply a function per group | with(df, tapply(cpu, role, max)) |
| merge(a, b, by = "k") | Join two data frames | merge(df, owners, by = "role") |
| rbind, cbind | Stack rows or columns | rbind(df1, df2) |
| split(x, g) | List of pieces per group | split(df$cpu, df$role) |
| transform(df, …) | Add computed columns | transform(df, cpu_frac = cpu / 100) |

```
df |> subset(role == "web") |> nrow()
mtcars |> lm(mpg ~ wt, data = _) |> coef()   # _ placeholder must be a named argument
```

## Lists, functions and the apply family

| Syntax | What it does | Example |
| --- | --- | --- |
| list(host = "web01", ports = c(80, 443)) | Container for mixed types, can nest | l$meta$os |
| l$key
