R Cheatsheet — Concise Reference
A cheatsheet for R 4.4 syntax, data structures and the most-used base R / tidyverse functions, covering about 80% of everyday scenarios.
R R 4.4
R (GNU R / interactive interpreter) · Functional · Vectorized · OO (S3 / S4 / R6) · Dynamic
Recommended Learning Path
Start by running Rscript and using assignment (<-) → master vectors, data.frame and the other data structures → write control flow with if/for and the apply family → learn functions, closures and the pipe |> → dig deeper into apply-style collection operations → understand S3/R6 object orientation and error handling → then pick up file I/O, parallelism, networking and regular expressions as needed. The FAQ section is worth revisiting to avoid pitfalls; package management and renv are covered in the build chapter.
1.Hello World and the runtime
Running with Rscript, the REPL, printed output, and the help system.
Minimal program
R evaluates expressions one at a time. `print` displays an object; `cat` writes raw output. Scripts run via `Rscript`.
Assignment and output
Use `<-` (or `=`) to assign. `print` shows object structure; `cat` is good for concatenated output. `message` writes to stderr.
Running Rscript
Rscript runs a script non-interactively — ideal for batch jobs and the command line. `source` runs a script inside an interactive session.
Command-line arguments
`commandArgs(trailingOnly = TRUE)` returns the arguments that follow the script name; all values are strings.
Printed output
`print` shows the object and its structure; `cat` concatenates without quotes; `sprintf` formats. `invisible` suppresses auto-printing.
Help docs
`?` opens the help page; `??` does a full-text search. `args` lists the formal arguments; `example` runs the examples.
Loading packages
`library` attaches a package to the search path; `require` returns a logical. `::` calls a function from a specific package.
Running a script
`source` runs the file in the current session, defining its functions and variables. `echo = TRUE` shows each line as it executes.
2.Variables and constants
Assignment, basic types, `NA`/`NULL`, and type coercion.
Assignment operators
`<-` is the idiomatic assignment; `=` also works. `<<-` writes to an outer variable from inside a function. Use `assign()` for fully global assignment.
Basic types
Atomic vectors come in `numeric`, `integer`, `character`, and `logical`. Append `L` to mark an integer. `typeof()` reveals the underlying storage type.
NA and NULL
`NA` marks a missing value; `NULL` represents an empty object. Check with `is.na()` / `is.null()`. `NaN` is Not-a-Number; `Inf` is infinity.
Type coercion
`as.*()` performs an explicit coercion. `c()` auto-coerces mixed types to the most general one. Use `is.*()` to test.
Creating vectors
`c()` concatenates; `:` generates a range; `seq()` controls the step; `rep()` repeats. Assign `names()` to label elements.
Naming conventions
Names allow letters, digits, dots, and underscores, but may not start with a digit. The dot has no operator meaning in R.
Managing variables
`ls()` lists variables; `rm()` removes them. `exists()` checks for presence. `rm(list = ls())` empties the environment.
Built-in constants
R ships handy constants: `pi`, `letters`, `month.name`, plus `.Machine` for platform particulars.
Scope basics
R uses lexical scoping: a function searches enclosing environments outward. A local name shadows the global. `get()` reads from a chosen environment.
3.Data types and structures
Vectors, factors, matrices, lists, data frames, and tibbles — R's data-structure hierarchy.
Vectors
Atomic vectors are homogeneous and one-dimensional — R's most basic structure. Build with `c()`; indexing starts at 1.
Factors
Factors store categorical variables with fixed `levels`. Ordered factors capture order. Create with `as.factor()` / `factor()`.
Matrices
`matrix()` builds a 2D homogeneous array. `byrow` controls the fill direction. Set row/column names via `dimnames`.
Arrays
`array()` makes a homogeneous structure of any dimension. `dim` sets the length along each axis. Useful for multi-dimensional tensors.
Lists
`list()` is heterogeneous and nestable. Use `$` or `[[` to extract an element; `[` returns a sub-list. `length()` counts elements.
Data frames
A `data.frame` is tabular data with heterogeneous columns. Default `stringsAsFactors = FALSE` since R 4.0. Inspect with `str()` / `head()`.
tibble
A `tibble` is the tidyverse's modern data frame: lazy columns, friendly printing, and never coercing strings to factors.
Attributes
`attributes()` carry metadata: `names`, `dim`, `class`, etc. `attr()` reads/sets one attribute. `structure()` builds an object with attributes in a single call.
Type checks
`is.*()` tests the type; `class()`/`typeof()`/`mode()` reveal it. `as.*()` converts. Use things like `is.data.frame` to branch.
4.References and object semantics
R has no raw pointers: copy-on-modify gives value semantics; environments provide reference semantics.
Copy-on-modify
R uses copy-on-modify: assignments share the underlying data, and a real copy happens only on modification. Aliasing big objects is nearly free.
tracemem for copy tracking
`tracemem()` tags an object; R prints the address change whenever a real copy happens. It helps diagnose unexpected copies and memory overhead.
Environments as references
An `environment` is R's reference object: passing it doesn't copy, and modifications inside a function take effect immediately — the closest thing R has to a pointer.
Mutable state containers
Environments serve as mutable state containers: counters, caches, accumulators. Avoid polluting the globals by passing state explicitly.
Shallow vs. deep copies
List assignment is a shallow copy: sub-objects are shared, so editing a nested element copies that level. Deep copies must be implemented explicitly.
R6 reference classes
R6 classes use reference semantics: objects are passed by reference, and methods mutate the original rather than a copy — well suited for state management.
data.table references
`data.table` mutates in place with `:=` (reference semantics); `data.frame` is copy semantics. `setDT()` converts to `data.table` in place.
Object size
`object.size()` measures one object; `gc()` reports overall memory. `lobstr::obj_size()` accounts for sharing.
Explicit copies
When you really need an independent copy: recursively copy a list with `lapply()`, copy a `data.table` with `copy()`, and copy a vector with `[]`.
5.Control flow
`if` / `else`, the vectorised `ifelse`, `for` / `while`, `switch`, and logical operators.
if / else
An `if` condition must have length 1. Anything else takes the first element and warns. Place `else` on the same line as the closing brace.
Vectorised ifelse
`ifelse()` tests elementwise over a vector and returns a result the same length as the condition — handy for bulk replacement.
for loops
`for` iterates over a vector or sequence. Prefer `seq_along()` for index loops to avoid the empty-sequence trap of `1:length()`.
while and repeat
`while` tests the condition before each iteration; `repeat` loops unconditionally, relying on `break` to exit. Guard against infinite loops in both.
next and break
`next` jumps to the next iteration; `break` exits the loop — ideal for skipping or early termination.
switch
`switch()` dispatches by position or name. A numeric value picks the nth branch; a string matches a named branch; otherwise it returns `NULL`.
Vectorisation over loops
R replaces explicit loops with vectorization: operate on whole vectors at once, faster and more concise. Reserve loops for cases that cannot be vectorized.
Logical Operators
& and | are vectorized logical operators; && and || evaluate only the first element (short-circuit). any/all summarize.
Index Iteration
seq_along / seq_len generate indices, rev reverses order. which returns positions. split iterates over groups.
6.Functions and Closures
Function definition, arguments, lazy evaluation, variadic arguments, closures, and pipes.
Function Definition
function defines a function; the last expression in the body is the return value. Anonymous functions are used directly as arguments.
Arguments and Defaults
Function arguments can have default values. Calls may omit argument names and pass by position, or use named arguments. missing checks whether an argument was supplied.
Lazy Evaluation
R uses lazy evaluation for arguments: evaluated only when used, and unreferenced arguments do not error. force forces early evaluation. This is critical in closures.
Variadic Arguments
... captures any number of arguments. list(...) collects them, do.call dynamically invokes a function with a list.
Return Values
A function returns the last expression. return exits early. invisible returns a value without auto-printing.
Closures
A function captures the environment in which it was created and can carry private state. Factory functions generate new functions with state.
Anonymous Functions
Anonymous functions are function literals, commonly used with the apply family and purrr. R 4.1+ supports the \(x) shorthand.
Higher-Order Functions
Functions can be passed as arguments to other functions and can also return functions. Map / Reduce / Filter are built-in higher-order functions.
Pipes
|> is the native pipe that passes the left-hand result as the first argument to the right-hand function, turning nested calls into a linear flow. %>% is the magrittr version.
7.Strings
Character vectors, concatenation, substring, splitting, regex, and formatting.
String Basics
Character vectors are quoted; double and single quotes are equivalent. nchar returns length, [] extracts a character. Backslashes need escaping.
Concatenation
paste uses a space as the default separator; paste0 uses no separator. collapse joins an entire vector into a single string. Concatenation is vectorized.
Substring
substr / substring extract by position; [] with brackets takes a single character. strsplit splits.
Splitting
strsplit splits by a delimiter into a list. unlist flattens. A regex can also serve as the delimiter.
Regex Functions
grep / grepl match, gsub / sub replace. All operate vectorized element-wise. See the regex chapter for details.
Formatting
sprintf mimics C printf formatting. %s for strings, %d for integers, %f for floats. formatC / round control numbers.
Case and Trimming
toupper / tolower convert case, trimws removes whitespace. chartr performs character translation. Commonly used when processing tool names.
Encoding
R strings are primarily UTF-8. Encoding inspects the encoding, enc2utf8 converts, iconv transcodes.
stringr
A tidyverse string-handling package. Functions share a unified str_ prefix: str_detect / str_replace / str_extract.
8.Sets and the apply Family
apply / lapply / sapply for batch iteration, sort, deduplication, set operations, and dplyr data manipulation.
lapply and sapply
lapply applies a function element-wise over a list or vector and returns a list. sapply tries to simplify the result into a vector or matrix.
apply
apply operates along a dimension of a matrix or array. MARGIN=1 is row-wise, 2 is column-wise. The return value is assembled by dimension.
mapply: Multiple Arguments
mapply applies a function in parallel over multiple arguments, corresponding to Map. Shorter arguments are recycled. SIMPLIFY controls simplification.
split: Grouping
split splits a vector into a list of groups by a factor. Combined with lapply it performs group-wise summaries, equivalent to group-by.
Sorting and Ranking
sort sorts a vector, order returns the sort indices, rank returns ranks. decreasing controls the direction. Data frames are sorted by column.
Deduplication
unique removes duplicates, duplicated flags duplicate entries. Among duplicate rows, the first is kept. all.equal compares vectors.
Set Operations
union / intersect / setdiff are set operations. %in% tests membership. After unique, take intersections, unions, and differences.
List Operations
Combine lists, flatten, and rename in bulk. unlist recursively flattens, do.call binds into an array. purrr provides typed operations.
dplyr Data Manipulation
select / filter / mutate / arrange / summarise manipulate data frames in a pipeline; group_by groups. Core tidyverse.
9.Memory Management
Garbage collection, object size, copy cost, preallocation, and performance profiling.
Garbage Collection
R uses automatic reference counting plus cyclic GC. gc triggers collection manually and reports. Call it after large-data loops.
Object size
object.size inspects the byte size of a single object. format converts to a readable unit. Estimate memory for large datasets.
Copy Cost
R's value semantics copy the entire object on modification, so mutating large objects is expensive. Avoid frequent in-place edits to large vectors.
Preallocation
Allocate a result vector of the final length first, then fill it in a loop, avoiding repeated concatenation and copying. Preallocate numeric/character vectors.
Vectorization and Performance
Prefer whole-vector operations. Row-binding with rbind is slow; use do.call(rbind, list) or data.table. Run microbenchmarks.
Memory Limits
memory.limit (Windows) inspects or adjusts the limit. object.size checks size. ulimit affects the session.
Profiling
Rprof records function-call timings. summaryRprof summarizes. system.time gives coarse timing. profvis visualizes.
data.table Memory
data.table uses reference semantics to reduce copies: := modifies in place, setDT converts, copy clones explicitly. Saves memory on large datasets.
10.Object-Oriented Programming (S3 / S4 / R6)
S3 simple generics, S4 formal classes, and R6 reference classes: three OO systems, each with its own role.
S3 Class Basics
S3 is R's lightweight OO: a class attribute plus generic functions. unclass reveals the underlying object. Most commonly used and lightweight.
S3 Methods
Defining a function named class.method implements a generic. UseMethod dispatches. NextMethod calls the parent method.
S3 Constructors
Custom classes should provide a constructor and validation. structure sets the class in one step. print / summary customize output.
S4 Classes
S4 is formal OO: setClass defines slots, validity validates, setGeneric / setMethod define generics.
R6 Classes
R6 is an encapsulated class with reference semantics; access members with self$ inside methods. Its object-oriented model feels closer to other languages.
Generic dispatch
Dispatch uses the object's class attribute; UseMethod finds the matching method by class. Legacy classes (S3) are tried one layer at a time.
Inheritance
S3 inherits through the class attribute (NextMethod chain), S4 uses contains, R6 uses inherit.
Comparing the three systems
S3 is lightweight and used by most packages; S4 for rigorous definitions; R6 with reference semantics fits stateful objects. In practice the three are often mixed.
class and attributes
class is a special attribute used by generics for dispatch. attr adds custom attributes that do not affect dispatch. class<- sets the class directly.
11.Error handling
stop for errors, warning for warnings, tryCatch for capture, and the condition system.
stop for errors
stop throws an error and halts execution. stopifnot quickly asserts a condition. Error messages should clearly explain the cause.
warning
warning emits a non-fatal notice without interrupting execution. suppressWarnings silences them. options(warn=2) upgrades them to errors.
tryCatch
tryCatch captures errors/warnings and returns the handler's result. It has three parts: error, warning, and finally.
try for fault tolerance
try returns the expression's value, or on failure an object of class try-error, without halting the whole flow. Common in batch processing.
Condition system
R's errors, warnings, and messages are all condition objects. signalCondition raises them; withCallingHandlers catches and continues.
Intercepting warnings
withCallingHandlers catches warnings without halting execution so you can log them and continue. Combine it with invokeRestart.
restarts
An advanced signal-handling mechanism: the caller can provide recovery actions. invokeRestart fires one from the catching side.
Errors inside loops
During batch processing, a single failure should not abort the whole run. tryCatch each item for fault tolerance and keep the surviving results.
Custom errors
A custom error class carries extra fields. Construct one with simpleError or structure; mark the type with class.
12.File and data I/O
CSV, readr, line-by-line reading, RDS, JSON, connections, and binary I/O.
CSV read/write
read.csv / write.csv read and write CSV. stringsAsFactors=FALSE prevents conversion to factors. check.names cleans column names.
readr read/write
readr is tidyverse's fast CSV reader. read_csv auto-detects column types; write_csv writes quickly.
Line-by-line reading
readLines reads a file into a character vector, one line per element. writeLines writes it back. Read large files in chunks.
read.table
read.table is the general table reader; read.csv is a variant of it. Common arguments include header, sep, and na.strings.
RDS storage
saveRDS writes a single R object; readRDS restores it. Type and attributes are preserved, which makes it more complete than CSV.
JSON read/write
jsonlite is the main JSON package. fromJSON parses, toJSON serializes. Line-delimited JSON handles API responses.
Connections
A connection abstracts a data source such as a file or a network stream. file opens it; readLines / writeLines read or write; close closes it.
Binary read/write
readBin / writeBin read and write binary data. The raw type holds bytes. Use binary I/O for large files and image data.
Other formats
readxl reads Excel; haven reads SPSS/Stata; feather/parquet are columnar formats. Load them on demand.
13.Common pitfalls
Pitfalls R users hit most often, and how to write the code correctly.
Condition length is not 1
if requires a length-1 condition; with a vector it tests only the first element and warns. Summarize with any/all, or vectorize with ifelse.
Factor to numeric
as.numeric on a factor returns the internal integer codes. Convert to character first to get the real values.
Dimension drop
Subsetting a matrix to a single row or column drops it to a vector by default. drop = FALSE preserves the dimensions.
Growing a vector in a loop
c() inside a loop copies the whole vector every iteration, which is extremely slow. Pre-allocate, or vectorize.
NA and comparisons
An NA in a comparison yields NA, never FALSE. Filter NA out with is.na.
Partial matching
$ and [[ perform unique-prefix matching. This silent abbreviation of names hides bugs; use full names, or use dplyr.
Vector recycling
Shorter vectors are recycled to the length of the longer one in operations. When the lengths are not a multiple, you only get a warning — bugs hide easily.
List flattening
c() tries to flatten one level of lists. Wrap elements in list() to keep them as a list. unlist recurses and can bite you.
Package masking
library-loaded packages mask functions with the same name; later entries in the search path hide earlier ones. Disambiguate with ::.
14.Parallel and concurrent
parallel, mclapply, foreach, and future: R's multiprocess parallelism toolkit.
parallel overview
R's parallelism is multiprocess (fork) or socket-based. The parallel package provides mclapply and clusters. There is startup overhead, so tasks need to be large enough to pay for it.
mclapply
mclapply is parallel's parallel lapply, implemented with fork. Available only on Unix (Windows needs a cluster).
Cluster parallelism
makeCluster creates a process cluster; parLapply applies a function in parallel. Works on Windows too. Call stopCluster when done.
foreach
foreach collects results across iterations; %dopar% runs in parallel (needs doParallel). %do% is the sequential variant.
future
The future package models parallelism as a "future value." future() launches an async task; value() retrieves it. plan chooses the strategy.
Shared state
Parallel workers do not share memory: each copies its own environment. Guard file writes against concurrent conflicts, and collect results via return values.
Random seeds
Each worker needs its own seed in parallel runs. Combine set.seed globally with clusterSetRNGStream (or future.seed) to keep results reproducible.
Parallel performance
Gains are limited by task granularity, core count, and communication overhead. Profile the serial bottleneck first, then parallelize the biggest chunk.
15.HTTP requests
Downloads, httr2/httr requests, JSON APIs, URL handling, and web scraping.
Downloading files
download.file fetches a file. mode controls binary mode. R.utils supports resuming partial downloads. Set timeout on slow links.
httr2 requests
httr2 is the next-generation HTTP client. req_perform sends a request; resp_body_json parses the response. Build requests in a pipeline.
GET Requests
GET reads a resource. Base R's readLines can pull plain text; httr's GET plus content parses the response. Query parameters are appended to the URL.
POST Requests
POST submits data. The body carries JSON or form fields. Two styles are common: httr POST and httr2 req_body_json.
JSON APIs
Calling a JSON API means a request plus jsonlite parsing. The result is often a nested list, so flatten it into a data frame. Mind pagination and error handling.
URL Handling
parse_url splits a URL into components and URLencode escapes it. URLdecode reverses the encoding. Base R covers this out of the box.
Web Scraping
rvest parses HTML. html_elements selects nodes and html_text extracts the text. Respect robots rules and rate limits.
TCP Sockets
socketConnection opens a TCP connection for reading and writing strings. It suits simple protocols and internal services.
16.Time and Dates
Sys.Date / POSIXct, formatting, lubridate and time zones.
Current Time
Sys.Date gives today's date and Sys.time the current date-time. date returns the current time as a string.
Date Basics
The Date class is R's date type. as.Date converts strings, and you can add or subtract days. unclass reveals the underlying day count.
POSIXct
POSIXct stores a second-level timestamp, while POSIXlt breaks it into components. as.POSIXct parses strings and handles time zones.
Formatting
strftime / format output according to placeholders. %Y year, %m month, %d day, %H hour, %M minute, %S second.
lubridate Overview
lubridate offers friendly date functions: ymd / ymd_hms for parsing, year / month for components, and interval arithmetic.
Date Sequences
seq generates date sequences with by set to day, month or year. Use seq.Date for arbitrary intervals and business days.
Time Differences
Subtracting dates yields a difftime. units sets the unit and as.numeric extracts the number. Handy for timing code.
Time Zones
The tz argument sets the time zone. Sys.timezone reports the current one and OlsonNames lists the valid names. Use them to compare instants across zones.
17.Processes and Environment
Running system commands, environment variables, command-line arguments, platform information and paths.
Running Commands
system runs a system command and returns its exit code. system2 passes arguments more safely. Capture output with capture or intern.
Environment Variables
Sys.getenv reads and Sys.setenv writes. unsetenv removes a variable. PATH and R-related variables come up most often.
Command-line arguments
commandArgs retrieves script arguments. trailingOnly strips R's own arguments. Parse them with optparse or by hand in base R.
Exit Status
quit exits R. q('no') skips saving the workspace. Use quit(status = 1) to exit with an error so scripts can react.
Platform Information
R.version gives the version, Sys.info the system details and .Platform the platform specifics. Useful for cross-platform concerns such as path separators.
Path Management
file.path joins paths, dirname / basename split them, and normalizePath produces a canonical absolute path. file.exists tests for existence.
Sleeping and Waiting
Sys.sleep pauses for a given number of seconds. Use it to rate-limit or to wait for an external resource. The unit is seconds.
Rscript Scripts
Rscript is the non-interactive entry point, ideal for scheduled jobs and batch processing. A shebang can go at the top of the script.
18.Regular Expressions
grep / grepl, gsub substitution, regexpr positions, stringr and common patterns.
grep and grepl
grep returns matching indices while grepl returns a logical vector. ignore.case makes matching case-insensitive. value returns the matched values.
gsub Substitution
gsub replaces every match, sub only the first. \\1 refers to a capture group. perl=TRUE enables the extended syntax.
regexpr Positions
regexpr returns the position and length of the first match, gregexpr all of them. regmatches extracts the matched text.
Syntax Basics
Core regex metacharacters: ^ start, $ end, . any, . character classes [], groups (), quantifiers * + ? {}, escaping \\.
Common Patterns
A quick reference of common patterns: email, phone, date, whitespace cleanup and number extraction. Tweak them to fit your needs.
stringr Matching
stringr keeps the same regex syntax but a consistent interface. str_detect / str_extract / str_match plus their _all variants.
stringr Substitution
str_replace / str_replace_all perform replacement. The pattern can use fixed or perl. str_remove deletes a match.
Flags and Extensions
perl=TRUE enables PCRE extensions such as lookahead and named groups. fixed=TRUE matches literally. ignore.case is also available.
19.Packages and Builds
CRAN installation, renv dependency management, package structure and R CMD, testthat, roxygen.
Installing Packages
install.packages installs from CRAN. update.packages upgrades. library loads a package. Use devtools / remotes for development versions.
CRAN and Repositories
CRAN is the official package repository. repos selects a mirror. available.packages lists what can be installed. CRAN policy governs releases.
renv Dependency Management
renv pins project dependency versions, much like Python's venv. renv::init sets it up, and snapshot / restore sync the lockfile.
Package Structure
The standard R package layout: DESCRIPTION, R/, man/, tests/, NAMESPACE. R/ holds the source and man/ the documentation.
R CMD Commands
The R CMD commands build and check packages: build packs, check validates, INSTALL installs. check is mandatory before release.
testthat Testing
testthat is the mainstream testing framework. expect_equal and friends are the assertions, and test_that organises cases. usethis generates the test files.
Formatting and Linting
styler enforces a uniform code style and lintr does static checking. Pair them with RStudio Addins or pre-commit to stay tidy.
roxygen Documentation
roxygen2 generates .Rd documentation from comments. Lines start with #' and use @param / @return / @export tags. The docs live next to the source.
Reproducible Sessions
sessionInfo records versions and dependencies for reproducibility. renv.lock pins the dependencies. Record the R version too.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for R 4.4, covering roughly 80% of the base R and tidyverse scenarios you meet in real data analysis. It leans toward modern idioms: the native pipe `|>`, the anonymous-function shorthand `\(x)`, `data.frame` with `stringsAsFactors = FALSE`, vectorized `ifelse`, typed collection operations via `purrr::map_*`, and R's distinctive copy-on-modify semantics alongside environment reference semantics. For authoritative material, see the official R manuals and R for Data Science. Nineteen chapters each focus on one topic — from your first program, variables and types through to the apply family, S3/R6 object orientation, parallelism and networking. Every chapter is split into 8–9 worked sections of 5–20 lines each, roughly 160 topics in total. The snippets are deliberately short and self-explanatory, ready to paste straight into R or RStudio. Everything runs in your browser — no uploads, no tracking. This page is part of the GuruToolkit collection of free developer tools; the snippets are free to use, with no warranty.
Version 2.1.0