R
Updated: September 10, 2025Categories: Languages, Stats
Printed from:
R Programming Cheatsheet
Language Overview
- Statistical computing and data analysis language
- Developed by Ross Ihaka and Robert Gentleman at the University of Auckland
- Open-source, primarily used for statistical analysis, graphics, and data science
- Supports functional, object-oriented, and imperative programming paradigms
Basic Syntax
r
1234# Single-line comment
print("Hello, R!") # Printing to console
x <- 10 # Assignment operator
Data Types (Primitive Types, Collection Types)
Primitive Types
r
1234567891011121314151617181920# Numeric
x <- 42.5
is.numeric(x) # TRUE
# Integer
y <- 42L
is.integer(y) # TRUE
# Character
name <- "R Programming"
is.character(name) # TRUE
# Logical
is_true <- TRUE
is.logical(is_true) # TRUE
# Complex
z <- 3 + 2i
is.complex(z) # TRUE
Collection Types
r
1234567891011121314151617# Vector (homogeneous)
numeric_vector <- c(1, 2, 3, 4, 5)
character_vector <- c("a", "b", "c")
# List (heterogeneous)
mixed_list <- list(1, "a", TRUE, 3.14)
# Factor (categorical variable)
gender <- factor(c("male", "female", "male"))
# Data Frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
stringsAsFactors = FALSE
)
Variables and Constants
r
123456789# Variable assignment
x <- 10 # Preferred method
y = 20 # Also works, but not recommended
x <<- 30 # Global assignment
# Constant (R doesn't have true constants)
# Use conventions or packages like 'constants'
PI <- 3.14159
Operators
Arithmetic Operators
r
123456789a <- 10
b <- 3
c <- a + b # Addition
d <- a - b # Subtraction
e <- a * b # Multiplication
f <- a / b # Division
g <- a %% b # Modulo
h <- a ^ b # Exponentiation
Comparison Operators
r
1234567x == y # Equal to
x != y # Not equal to
x < y # Less than
x > y # Greater than
x <= y # Less than or equal to
x >= y # Greater than or equal to
Logical Operators
r
12345TRUE & FALSE # Logical AND
TRUE | FALSE # Logical OR
!TRUE # Logical NOT
isTRUE(x) # Check if TRUE
Control Structures
Conditional Statements
r
12345678910111213141516# If-else
if (condition) {
# code
} else if (another_condition) {
# code
} else {
# code
}
# Switch statement
switch(x,
"a" = "First option",
"b" = "Second option",
"default"
)
Loops
r
12345678910111213141516# For loop
for (i in 1:5) {
print(i)
}
# While loop
while (condition) {
# code
}
# Repeat loop
repeat {
# code
if (condition) break
}
Functions
Basic Functions
r
12345678# Function definition
my_function <- function(x, y = 10) {
return(x + y)
}
# Anonymous function (lambda-like)
square <- function(x) x^2
Advanced Function Concepts
r
12345678910# Ellipsis for variable arguments
variable_args <- function(...) {
args <- list(...)
print(args)
}
# Functional programming with apply family
lapply(list(1, 2, 3), function(x) x^2)
sapply(list(1, 2, 3), function(x) x^2)
Data Structures
Vectors
r
123456789# Creating vectors
v1 <- c(1, 2, 3)
v2 <- seq(1, 10, by = 2)
v3 <- rep(1, times = 5)
# Vector operations
v1 + v2 # Element-wise addition
length(v1) # Vector length
Data Frames
r
1234567891011# Creating data frames
df <- data.frame(
name = c("Alice", "Bob"),
age = c(25, 30)
)
# Subsetting
df$name
df[1, 2] # First row, second column
subset(df, age > 25)
Object-Oriented Programming
S3 Classes
r
123456789# S3 class creation
person <- list(name = "John", age = 30)
class(person) <- "Person"
# Method definition
print.Person <- function(x) {
cat("Name:", x$name, "Age:", x$age, "\n")
}
Error Handling
r
1234567891011# Try-catch equivalent
tryCatch({
# code that might throw an error
}, error = function(e) {
print("An error occurred")
}, warning = function(w) {
print("A warning occurred")
}, finally = {
# cleanup code
})
File I/O
r
12345678# Reading files
read.csv("data.csv")
read.table("data.txt")
# Writing files
write.csv(df, "output.csv")
write.table(df, "output.txt")
Common Libraries and Frameworks
Data Manipulation
- dplyr: Data transformation
- tidyr: Data tidying
- data.table: Fast data manipulation
Data Visualization
- ggplot2: Advanced plotting
- plotly: Interactive plots
- lattice: Statistical plotting
Statistical Analysis
- stats: Built-in statistical functions
- car: Companion to Applied Regression
- lme4: Linear mixed-effects models
Package Management
r
123456789# Install package from CRAN
install.packages("ggplot2")
# Load package
library(ggplot2)
# Check installed packages
installed.packages()
Best Practices
- Use meaningful variable names
- Vectorize operations instead of using loops
- Leverage functional programming
- Use pipe operator (%>%) for readability
- Profile and optimize performance
Testing
r
1234567# Using testthat package
library(testthat)
test_that("Addition works", {
expect_equal(2 + 2, 4)
})
Reproducible Research
r
1234# R Markdown
library(rmarkdown)
render("report.Rmd")
Performance Optimization
- Vectorization
- Avoid growing objects dynamically
- Use specialized data structures
- Profile with
Rprof()
Resources for Further Learning
- R Project (r-project.org)
- RStudio (rstudio.com)
- CRAN Packages (cran.r-project.org)
- Coursera R Programming Course
- "R for Data Science" by Hadley Wickham
Continue Learning
Discover more cheatsheets to boost your productivity