List of R functions

From Opasnet
Jump to: navigation, search



This page contains listings of some R functions and commands by category. The format is pretty stupid but can't do much better with wiki formatting, sorry.

Workspace and help

Workspace and help
function name functionality
getwd() get working directory
setwd(dir) set working directory to dir
help(topic), ?topic get help on topic, usually function name
help.search("keyword") search for help
help.start() HTML help start page
demo() list available demonstrations
save(..., file), load(file) save and load objects
savehistory(file), loadhistory(file) save and load command history
source(file) execute commands from file
list.files(dir), dir(dir) list files in directory dir
q() quit R

Objects

Objects
function name functionality
mode(x) mode of x
ls(), objects() list objects in memory
rm(x), rm(list = ls()) remove x or all objects
exists(x) test if object x exists in memory
as.numeric(x), as.list(x), as.character(x), as.factor(x), as.data.frame(x),... coerce mode of object x
is.numeric(x), is.na(x), ... test mode of object x
identical(x, y) test if objects are identical
return(invisible(x)) return invisible copy (doesn't print)

Packages

Packages
function name functionality
install.packages(name) download and install package name
download.packages(name, dir) download package name into dir
library(name), require(name) load package name
data(name) load dataset name
.libPaths(dir) add directory dir to library paths
sessionInfo() list loaded packages

Flow and control and function definition

Flow and control and function definition
function name functionality
if(logical_expression) {expression_1} else {expression_2} if then else
for (x in vector) {expression} loop through elements of vector as x
while (logical_expression) {expression} while loop
name <- function(input1, ...) {expression_1; ...; return(output)} function definition
stop(message) cease processing and print message
browser() stop to inspect objects for debugging
system.time(expression) report runtime for expression

Mathematical and logical operators and functions

Mathematical and logical operators and functions
function name functionality
+, -, *, /, ^, %%, %/% algebraic operators, %% for remainder of integer division, %/% for integer division i.e. rounded down to 0 decimal places
<, >, <=, >=, ==, != comparison operators (less than, greater than, less or equal, greater or equal, equal, not)
&, |, ! logical operators (and, or, not)
&&, || and/or evaluated progressively from left
xor(A, B) exclusive or (A or B but not both)
ifelse(condition, x, y) choose x or y elementwise
sin(x), cos(x), tan(x) sine, cosine and tangent
asin(x), acos(x), atan(x) inverse sine, cosine and tangent
exp(x), log(x) exponential and logarithm base e
sqrt(x) square root
abs(x) absolute value
pi 3.1415926...
ceiling(x) smallest integer >= x
floor(x) largest integer <= x
all.equal(x, y) almost equal
round(x, k) round x to k digits
deriv(expression, vars) symbolic differentiation

Vectors

Vectors
function name functionality
x[i] select subvector from x using index vector i
x[logical], subset(x, subset) select subvector using logical vector
c(x, y,...) combine vectors x, y, ...
seq(from, to, by), from:to generate an arithmetic sequence
rep(x, times) generate repeated values
length(x) length of x
which(x) indices of TRUE elements of x
sum(...) sum over vector(s)
prod(...) product over vector(s)
cumsum(x), cumprod(x) cumulative sum and product
min(...), max(...) minimum and maximum
sort(x) sort a vector
mean(x) sample mean
var(x), sd(x) sample variance and standard deviation
order(x) rank order of elements of x

Matrices

Matrices
function name functionality
matrix(data, nrow, ncol, byrow) create a matrix
rbind(...), cbind(...) combine rows or columns
diag(x) create a diagonal matrix
 %*% matrix multiplication
nrow(A), ncol(A) number of rows and columns
colMeans(A), colSums(A) column means or sums
dim(A) dimensions of x
det(A) determinant
t(A) transpose
solve(A, b) solution of A x == b
solve(A) matrix inverse
array(data, dim) create a multidimensional array
reshape(data, idvar="id", timevar="a", v.names="b", direction="wide") reshape long data to wide (b=the values you want to show up under your new columns, id=the id that you want to group your data record by; a=the values that you want to make up the new columns; however many distinct values are in this column determines the number of new columns; wide= the destination or resulting format we want)
melt(data, id.vars = c("a"), variable_name = "b" reshape data wide to long; you need library(reshape); a=the values you want be indices; b the name of result column

Dataframes, factors and lists

Dataframes, factors and lists
function name functionality
data.frame(...) create a dataframe
str(x) summarise structure of x
names(x) names of x
dim(x) number of rows and columns of x
attach(x) copy dataframe objects into workspace
detach(x) delete dataframe objects from workspace
factor(x) create a factor
levels(x) select levels of factor x
list(...) create a list
unlist(x) flatten list x into a vector
apply(x, i, f, ...) apply function f over index i of array x
sapply(x, f, ...) apply function f to x and return a vector
lapply(x, f, ...) apply function f to x and return a list
tapply(x, i, f, ...) apply function f to subvectors of x given by levels of factor i
mapply(f, ...) apply function f to multiple arguments

Input and output

Input and output
function name functionality
scan(file, what, n, sep, skip) read from a file (or keyboard)
read.table(file) read file in table format into dataframe
read.csv(file) read comma separated data (read.table is recommended instead)
read.delim(file) read tab-delimited data (read.table is recommended instead)
readline(prompt) read a line of text from the console i.e. user input
show(object) display object on screen
head(object) first few lines of object
tail(object) last few lines of object
print(object), object print object
options(digits = x) display x digits in output
cat(..., file) concatenate and write
format(x, digits, nsmall, width) format x for output
paste(..., sep = " ") paste strings together with separator sep
write(x, file, append = FALSE) write to a file (or screen)
sink(file) redirect output to a file
dump("x", file) write text representation of x
write.table(x, file) write dataframe x to a file

Plotting

Plotting
function name functionality
plot(x, y) plot y against x
 :type = "?" determine the type:
 ::"p", "l", "b" for points, lines or both
 ::"c" for the lines part alone of "b"
 ::"o" for both lines and points overplotted
 ::"h" for vertical lines (histogram like plot)
 ::"s", "S" for step function, across/op or reverse
 ::"n" no data plotted, only axes
 :main = "title" provides plot title
 :xlim = c(a,b) set lower and upper limits of x-axis
 :ylim = c(a,b) set lower and upper limits of y-axis
 :xlab = "?", ylab = "?" provide label for x-axis and y-axis
 :pch = k set shape of points (k from 1 to 25)
 :lwd = ? set line width, default 1
 :col = "?" set line and point colour
colour(), color() list R colours
lines(x, y) add lines to plot
abline(h), abline(v) draw horizontal and vertical lines
points(x, y) add points to plot
text(x, y, labels) place text on plot
curve(f, from, to) plot f
par(?) set graphical parameters:
 :mfrow = c(nr, nc) create grid of plots with nr rows and nc columns filled by row (mfcol fills by col)
 :oma = c(b, l, t, r) create outer margin around each plot
 :mar = c(b, l, t, r) create margin around each plot
 :las = 1 make y-axis labels horizontal
 :pty = "s" force the plot shape to be square
 :cex = x magnify symbols and text by a factor x
 :bty = "?" determine box type drawn around plot

Random numbers and probability distributions

Random numbers and probability distributions
function name functionality
ddist(x, p1, ...) P(X=x) or f(x)
pdist(q, p1, ...) P(X<=q)
qdist(p, p1, ...) p-th quantile, equivalently 100%-point
rdist(n, p1, ...) pseudu-random numbers
dist p1, ... distribution and parameters
 :unif min = 0, max = 1 uniform
 :binom size, prob binomial
 :geom prob geometric
 :hyper m, n, k hypergeometric
 :nbinom size, prob negative binomial
 :poist lambda Poisson
 :exp rate exponential
 :chisq df chi square
 :gamma shape, rate gamma
 :norm mean, sd normal
 :t df t distribution
 :weibull shape, scale Weibull
set.seed(seed) set position in pseudo-random sequence
.Random.seed state if the random number generator
RNGkind() which random number generator?
sample(x, n, replace = TRUE) sample size n from x

Statistical tests

Statistical tests
function name functionality
t.test en:Student's t-test
aov en:Analysis of variance

References

Most of the listings are a pretty straight rip-off from the last pages of the book "Introduction to Scientific Programming and Simulation Using R" by Owen Jones, Robert Maillardet and Andrew Robinson, an excellent book by the way. Added some specifics and will edit the format later, so this is only a quick template, maybe.