Bold: commands/functions in Week 2.

Basic Commands

Command Purpose Example
? pull up a help page ?seq
: colon operator(generate regular sequence) 1.5:4
<- assignment x <- 5 + 7
c concatenate c(1.1, 9, 3.14)
seq, seq_along sequence generation seq(1,10,0.5)
length return the length of a vector length(pi:100)
rep replicate elements of vectors rep(c(1,2,3),5)
print prints its argument print(5:10)
# comment character # ignore the rest of line
class return the class of object class(pi)
as.numeric, as.integer,… explicit coercion as.integer(pi)
matrix create a matrix matrix(1:6, nrow=2, ncol=3)
dim return the dimension attribute of object dim( matrix(1:6, nrow=2, ncol=3) )
cbind, rbind create matrix by column-/row- binding vectors cbind(1:3,4:6)
list create a list list(name=“John”, age=20)
factor create a factor factor(“blue”,“green”,levels=c(“red”,“green”,“blue”))
is.na, is.nan check if the argument is NA (or NaN) is.na(as.numeric(“abc”))
data.frame create a data frame data.frame(foo = 1:4, bar = c(T, T, F, F))
nrow, ncol return the number of rows/columns of object nrow(data.frame(foo = 1:4, bar = c(T, T, F, F)))
names names of elements of a vector names(x)
colnames, rownames column/row names of a matrix/data frame colnames(m)
paste concatenate strings paste(“aa”,“bb”,“cc”,sep=“:”)
sum summation of elements in a vector sum(c(1,5,12))
prod product of elements in a vector prod(c(3,15,-2))
max, min maximum/minimum value in a vector max(c(23,12,12,3))
mean, median mean/median of a vector mean(c(1,5,1,2,7))
sort sorting sort(c(1,5,1,pi,2,7))
var, sd sample variance/standard deviation of a vector sd(c(1,5,1,3,2))
cor correlation cor(c(1,4,6,1), c(2,5,1,9))
which.min, which.max first index of minimum/maximum value which.min(c(4,1,3,4,1))


Logical Operators

Operator Name Example
>, < greater/less than 1:5 > seq(0,8,2)
== equality operator 1:5 == seq(0,8,2)
>=, <= greater or equal to/less than or equal to 1:5 <= seq(0,8,2)
!= not equal to 1:5 != seq(0,8,2)
! NOT !(1 > 2)
& AND (3:5 > 5:7) & (4:6 == 4:6)
| OR (3:5 > 5:7) | (4:6 == seq(2,6,2))


Mathematical Functions

Function Name Example
abs absolute value abs(3-6) = 3
sqrt square root sqrt(16) = 4
^ exponentiation 3^10 = \(3^{10}\) = 59049
exp exponential function exp(1.7) = \(e^{1.7}\) = 5.473947
log log function (base e) log(10) = 2.302585
log10 base 10 log (\(\log_{10}\)) log10(100) = 2
pi mathematical constant \(\pi\) pi = 3.141593
sin, cos, tan trigonometric functions (argument in radians) sin(pi/2) = 1
asin, acos, atan inverse trigonometric functions acos(1) = 0
sinh, cosh, tanh hyperbolic functions cosh(0) = 1
asinh, acosh, atanh inverse hyperbolic functions atanh(tanh(12)) = 12
round(x,n) round x to n decimal places round(pi,2) = 3.14
floor rounds down floor(14.7) = 14
ceiling rounds up ceiling(14.7) = 15