R: reference
The language of statistics and data analysis: vectors, data frames, functions and plots.
Program structure
Minimal program
There is no separate main: the script runs from top to bottom. print shows a value with the [1] index, and cat outputs text as is. In the console an expression prints its own result.
print("Hello, world!")
cat("No line break\n")
cat("a", "b", 42, "\n")
# comment to the end of the line
2 + 3Running
Scripts with the .R extension are run by Rscript. The -e flag runs a single expression, and the R command opens an interactive console that is handy for trying code.
Rscript hello.R Rscript -e "print(2 + 3)" R # interactive console
Variables and types
Assignment
The main assignment operator in R is <-, although = works too. Variables are created without declaring a type, and names are case-sensitive.
x <- 10 y = 5 20 -> z name <- "Olena" x <- x + 1 print(c(x, y, z)) print(name)
Basic types
Main types: integer (with the L suffix), numeric, character, logical, complex. NULL means the absence of an object, and NA marks a missing value.
print(class(42L))
print(class(3.14))
print(class("text"))
print(class(TRUE))
print(class(NULL))
print(class(3 + 2i))
print(class(NA))Type conversion
The functions as.numeric, as.integer, as.character convert the type. A failed conversion gives NA with a warning, and is.numeric and similar functions check the type.
print(as.numeric("12") + 1)
print(as.integer(3.9))
print(as.character(42))
print(as.logical("TRUE"))
print(is.numeric(5))
print(as.numeric("abc"))Strings
paste and paste0
paste joins parts with a space, paste0 with no separator. The sep parameter sets the separator, and collapse merges a vector into one string.
a <- "Hello"
b <- "World"
print(paste(a, b))
print(paste0(a, b, "!"))
print(paste("x", 1:3, sep = "-"))
print(paste(c("a", "b"), collapse = "+"))String functions
nchar counts characters, and substr cuts a part using positions starting from 1. sub and gsub replace by pattern, grepl tests for a match, and sprintf formats as in C.
s <- "Hello, World"
print(nchar(s))
print(toupper(s))
print(substr(s, 1, 5))
print(sub("World", "R", s))
print(strsplit(s, ", ")[[1]])
print(grepl("World", s))
print(sprintf("%s: %d, %.2f", "x", 7L, 3.14159))Conditions
if, else if, else
The condition goes in round parentheses, and else is placed on the same line as the closing }. Use && and || for single logical values, and & and | for vectors.
n <- 15
if (n < 10) {
print("few")
} else if (n < 20) {
print("medium")
} else {
print("many")
}
print(n != 15 || n > 5)ifelse and switch
ifelse applies the condition to every element of a vector. switch picks a value by name, and the last unnamed argument serves as the default.
x <- c(5, 12, 8, 20) print(ifelse(x > 10, "big", "small")) day <- "tue" res <- switch(day, mon = "Monday", tue = "Tuesday", "other") print(res)
Loops
for
for (x in vector) iterates over elements, and 1:3 creates a sequence that includes both bounds. seq sets a step, and seq_len(n) is a safe replacement for 1:n in empty cases.
for (i in 1:3) {
print(i)
}
for (w in c("a", "b")) {
cat(w, "")
}
cat("\n")
print(seq(10, 1, by = -4))
print(seq_len(3))while, repeat, break
while checks the condition before a step, and repeat loops forever until it meets break. The next statement skips the rest of the current iteration.
n <- 0
while (n < 3) {
n <- n + 1
}
print(n)
k <- 0
repeat {
k <- k + 2
if (k > 5) break
if (k == 2) next
print(k)
}Functions
Defining a function
A function is a value stored in a variable. The result is the last evaluated expression, so return is optional. Arguments can have defaults and be passed by name.
add <- function(a, b = 10) {
a + b
}
print(add(2, 3))
print(add(2))
print(add(b = 1, a = 5))
sq <- function(x) return(x^2)
print(sq(4))Variable number of arguments
Three dots ... accept any number of arguments, which are collected with c(...) or list(...). An anonymous function can be called right after it is defined.
total <- function(...) {
args <- c(...)
sum(args)
}
print(total(1, 2, 3, 4))
f <- function(...) length(list(...))
print(f("a", "b"))
print((function(x) x * 2)(21))Vectors and lists
Vectors
A vector is created by c(), and elements are numbered from 1. A negative index excludes an element, a logical mask v[v > 15] selects the needed ones, and names gives elements names.
v <- c(10, 20, 30, 40)
print(v[2])
print(v[-1])
print(v[v > 15])
print(length(v))
v <- c(v, 50)
names(v) <- c("a", "b", "c", "d", "e")
print(v["c"])Lists
A list holds values of different types. An element is taken with $ or [[ ]], while single [ ] return another list. Assigning p$key adds a new field.
p <- list(name = "Olena", age = 17, tags = c("a", "b"))
print(p$name)
print(p[["age"]])
p$city <- "Dnipro"
print(names(p))
print(length(p))
print(p$tags[2])Matrices
matrix fills the table by columns. An element is taken as m[row, column], dim gives the sizes, t transposes, and %*% performs matrix multiplication.
m <- matrix(1:6, nrow = 2) print(m) print(m[2, 3]) print(dim(m)) print(t(m)) print(m %*% t(m))
Vectorization and apply
Vector operations
Arithmetic in R works on a whole vector at once, so no loop is needed. A shorter vector is recycled to match the length, and sum, cumsum, rev also accept a vector.
x <- c(1, 2, 3, 4) print(x * 2) print(x + c(10, 20, 30, 40)) print(sqrt(x)) print(sum(x)) print(cumsum(x)) print(rev(x)) print(x %% 2 == 0)
sapply and lapply
lapply returns a list, sapply simplifies the result to a vector, and vapply also checks the result type. Map applies a function to several vectors in parallel.
x <- 1:4
print(sapply(x, function(v) v^2))
print(lapply(1:2, function(v) v * 10))
print(sapply(c("a", "bb", "ccc"), nchar))
print(vapply(x, function(v) v + 0.5, numeric(1)))
print(Map(function(a, b) a + b, 1:2, 3:4))apply for matrices
apply(m, 1, f) applies a function to every row, and apply(m, 2, f) to every column. For sums and means there are faster rowSums, colMeans and similar functions.
m <- matrix(1:6, nrow = 2) print(apply(m, 1, sum)) print(apply(m, 2, max)) print(rowSums(m)) print(colMeans(m))
Data tables
data.frame
A data.frame is a table where each column is a vector of its own type. nrow and ncol give the sizes, $ takes a column, and str shows the structure.
df <- data.frame(
name = c("Ann", "Bob", "Eva"),
age = c(21, 35, 28),
ok = c(TRUE, FALSE, TRUE)
)
print(df)
print(nrow(df))
print(df$age)
str(df)Selecting and filtering
In df[rows, columns] an empty part means everything. Rows are selected by a condition, a new column is added by assignment, and order returns indexes for sorting.
df <- data.frame(name = c("Ann", "Bob", "Eva"), age = c(21, 35, 28))
print(df[2, ])
print(df[df$age > 25, ])
print(df[, "name"])
df$senior <- df$age > 30
print(df[order(df$age, decreasing = TRUE), ])aggregate and merge
aggregate and tapply compute summaries by group. merge joins two tables on a shared column, similar to JOIN in SQL.
df <- data.frame(g = c("a", "b", "a", "b"), v = c(1, 2, 3, 4))
print(aggregate(v ~ g, data = df, FUN = sum))
print(tapply(df$v, df$g, mean))
info <- data.frame(g = c("a", "b"), label = c("first", "second"))
print(merge(df, info, by = "g"))Factors
factor and levels
A factor stores categories as integer codes with a set of levels. table counts how many times each level occurs, and as.integer shows the internal codes.
sizes <- factor(c("M", "S", "L", "M", "S", "M"))
print(sizes)
print(levels(sizes))
print(table(sizes))
print(nlevels(sizes))
print(as.integer(sizes))Ordered factor and cut
The levels parameter sets the order of levels, and ordered = TRUE lets you compare them. The cut function splits numbers into intervals and returns a factor.
lv <- factor(c("low", "high", "mid", "low"),
levels = c("low", "mid", "high"), ordered = TRUE)
print(lv)
print(lv[1] < lv[2])
ages <- c(5, 17, 30, 65)
print(cut(ages, breaks = c(0, 18, 60, Inf)))Statistics
mean, median, sd
mean is the average, median the median, sd the standard deviation, and var the sample variance. range returns the minimum and maximum as one vector.
x <- c(2, 4, 4, 4, 5, 5, 7, 9) print(mean(x)) print(median(x)) print(sd(x)) print(var(x)) print(range(x)) print(max(x) - min(x))
summary and quantiles
summary shows the minimum, quartiles, mean and maximum. quantile returns the requested percentiles, cor computes the correlation of two vectors, and round rounds the result.
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(summary(x)) print(quantile(x, c(0.25, 0.75))) y <- c(2, 4, 6, 8, 10, 12, 14, 16, 18, 21) print(cor(x, y)) print(round(cor(x, y), 3))
Missing values
NA infects calculations: mean returns NA. The na.rm = TRUE parameter ignores missing values, and is.na shows where they are. Use !is.na for filtering.
x <- c(4, NA, 6, 10) print(mean(x)) print(mean(x, na.rm = TRUE)) print(is.na(x)) print(sum(is.na(x))) print(x[!is.na(x)])
Plots
plot and lines
plot draws a basic graph, and type = "b" draws points with lines. Later calls to lines, abline and legend add elements on top of the current plot.
x <- 1:10
y <- x^2
plot(x, y, type = "b", main = "Squares",
xlab = "x", ylab = "y", col = "blue")
lines(x, x * 5, col = "red")
abline(h = 50, lty = 2)
legend("topleft", legend = c("x^2", "5x"),
col = c("blue", "red"), lty = 1)hist, barplot, boxplot
hist draws a histogram of a distribution, barplot a bar chart from table counts, and boxplot shows the median, quartiles and outliers.
x <- c(2, 3, 3, 4, 4, 4, 5, 5, 6, 9)
hist(x, breaks = 5, col = "gray", main = "Histogram")
barplot(table(c("a", "b", "a", "c", "a")))
boxplot(x, horizontal = TRUE)Saving a plot
The png function opens a file for drawing, and dev.off() closes it and saves. par(mfrow = c(1, 2)) splits the window into two plots side by side.
png("chart.png", width = 600, height = 400)
plot(1:5, c(2, 4, 3, 5, 1), type = "l")
dev.off()
par(mfrow = c(1, 2))
hist(c(1, 2, 2, 3))
boxplot(c(1, 2, 2, 3))Packages and data
library and install.packages
install.packages installs a package once, and library attaches it in each session. The form package::function calls a function without attaching the whole package.
install.packages("jsonlite")
library(jsonlite)
print(requireNamespace("stats", quietly = TRUE))
print(toJSON(list(a = 1, b = "x"), auto_unbox = TRUE))
stats::sd(c(1, 2, 3))Reading and writing CSV
write.csv saves a table to a file, and read.csv reads it back. head shows the first rows. The row.names = FALSE parameter does not add row numbers.
df <- data.frame(a = 1:3, b = c("x", "y", "z"))
write.csv(df, "data.csv", row.names = FALSE)
back <- read.csv("data.csv")
print(head(back, 2))
print(summary(back$a))
print(file.exists("data.csv"))What is next
A lessons course for this language is on the way, and the reference is already available.