8. Simulation by replicating a calculation
Make random number generation repeatable
set.seed(seed), for integer seed, sets starting point of (pseudo-)random number generation. e.g.
a = rnorm(1); b = rnorm(1); a = b
set.seed(0); a = rnorm(1); set.seed(0);
6. Statistical Tests and Condence Intervals
One Mean or the Dierence of Two Means
out = t.test(x, y = NULL, alternative = "two.sided", mu = 0, conf.level = .95) tests
H0 : X = 0 = mu for a sample x from a normal population; or, if y is given, H0 : X Y = 0
7. Simple Linear Regression, y = mx + b
e.g. cars is a built-in data.frame: cars, ?cars, str(cars), head(cars)
(Recall) plot(x, y) makes a (base graphics) scatterplot of data in the vectors x and y; e.g.
cor(x, y) gives t
5. (Base) Graphics
formula, data: a formula of the form y ~ model and a data frame containing the variables
main, sub; xlab, ylab: main title, subtitle; x-axis, y-axis labels
xlim, ylim, each a 2-vector (low, high): x-axis, y-axis lim
A vector (or one-dimensional array) v is a collection of values (or elements) of the same type, each
identied by an index in the range 1 to length(v). Combine values into a vector with c(.). e.g.
v <- c(2.71, 5, 3.14)
3. Vector (continued) and List
sort(x, decreasing = FALSE) returns a sorted copy of x. e.g. x = c(12, 11, 16, 11); sort(x)
v = rank(x, ties.method = "average"): v[i] is rank of x[i]; also try ties.method = "first"
4. Data Frame, Factor, Formula
Data Frame (Rs fundamental data structure)
A data.frame is () a list of equal-length vectors.
e.g. mtcars is a built-in data.frame: mtcars, ?mtcars, str(mtcars), summary(mtcars).
A factor represents a vector of catego
1. Conditional Expressions and Writing Functions
EXPRESSION runs only if CONDITION is TRUE. (Here UPPER.CASE is a placeholder for R code.)
if (CONDITION) cfw_
One of TRUE.EXPRESSION and FALSE.EXPRESSION runs:
2. Loops (through a sequence, 0 or more times, or 1 or more times)
Iterate through a sequence (vector or list)
This for loop runs EXPRESSION for each value VARIABLE in SEQUENCE. (UPPER.CASE text is a
placeholder for R code.)
for (VARIABLE in SEQUENCE) cfw
1. R as a Calculator (for Scalars)
x [+-*/^] y
x %/% y
x % y
log(x, base = exp(1)
(= indicates default)
cos(), sin(), tan()
Other easy functions:
round(x, digits = 0)