Author: Beau Christ
Basics
Basic arithmetic operators:
1 + 4 # addition
5 - 1 # subtraction
4 * 2 # multiplication
9 / 3 # division
4 ^ 2 # exponentiation
4 %% 2 # modulusTo assign values to variables:
x <- 3
"hello" -> nameSimple data types:
w <- 2.5634 # numeric
x <- TRUE # logical
y <- "Hi!" # character
z <- 500L # integerTo check a data type: class()
Vectors
A vector is a one-dimensional array with a single type
# create a new vector
u <- c(1, 10, 49)
# name the elements
names(v) <- c("A", "B", "C")
# add two vectors (result is vector)
r <- c(1, 5, 7) + c(2, 4, 5)
# sum the values
sum(v)
# compare two vectors (result is logical vector)
a > b
# select elements
a[3]
a[c(1,5)]
a[2:5]
# average the values in a vector
mean(v)
# logical selection
vect > 0 # returns logical indices
vect[vect > 0] # returns actual valuesMatrices
A matrix is a two-dimensional array with a single data type
# create a new matrix
matrix(1:9, byrow = TRUE, nrow = 3)
# name the rows/columns
colnames(mat) <- c("A", "B", "C")
rownames(mat) <- c("A", "B", "C")
matrix(..., dimnames = list(c("a", "b"), c("c", "d")))
# sum the rows/columns
colSums(mat)
rowSums(mat)
# bind (attach) a new row or column
cbind(mat, new)
rbind(mat, new)
# select values
mat[1,2]
mat[3,]
mat[c(1,6), 4:7]
# perform arithmetic (element-wise)
m / 5
mat1 * mat2Conditionals and Control Flow
TRUE evaluates to 1, FALSE evaluates to 0
Relational (comparison) operators: ==, !=, <, >, <=, >=
To obtain the first or last few elements:
head(values, 4) # get the first 4 elements
tail(values, 10) # get the last 10 elementsUseful tip: sum() can count the number of TRUE values.
Logical (boolean) operators: &, |, !
Conditional (if else) statements:
if (number < 10) {
if (number < 5) {
result <- "extra small"
} else {
result <- "small"
}
} else if (number < 100) {
result <- "medium"
} else {
result <- "large"
}Loops
# while loop
while (speed > 30) {
print("Slow down!")
speed <- speed - 7
}
# to stop a for/while loop
break
# for loop (version 1)
for (item in vec) {
print(item)
}
# for loop (version 2)
for (i in 1:length(vec)) {
print(vec[i])
}
# to continue to the next iteration
nextTo concatenate things together: paste() To split a string: strsplit(some_string, split = "")
Functions
Useful built-in functions include:
# mean/average
mean(x, trim = 0.2, na.rm = TRUE)
# standard deviation
sd()
# getting help, can also use '?'
help(sd)
?sd
# for viewing function arguments
args()
# absolute value
abs()
# load a package
library()
# install new packages
install.packages()
# round up or down (and optionally specify the number of digits after the decimal point)
round()
round(3.14159, digits = 2)
# sum values
sum()
# reverse items
rev()
# sort low to high
sort(, decreasing=)
# repeat a value
rep(, times=)
# create a sequence
seq(, , by=)To create a new function (return statement optional):
sum_abs <- function(x, y) {
abs(x) + abs(y)
}Plotting
To do a simple point plot, you provide the x and y values (these will be the x-y points):
x <- seq(0, 2*pi, 0.1)
y <- sin(x)
plot(x, y)
plot(x, y, col = "red", pch = 3) # Or optionally change the point character and color