1 Essential functions

a <- 5
die <- c(1,2,3,4,5,6)
ls()
## [1] "a"   "die"

R performs element-wise operations, not matrix-wise operations. But it can also do matrix multiplications.

die * die
## [1]  1  4  9 16 25 36
# inner multiplication:
die %*% die
##      [,1]
## [1,]   91
# outer multiplication:
die %o% die
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    2    3    4    5    6
## [2,]    2    4    6    8   10   12
## [3,]    3    6    9   12   15   18
## [4,]    4    8   12   16   20   24
## [5,]    5   10   15   20   25   30
## [6,]    6   12   18   24   30   36

More functions:

round(3.1416)
## [1] 3
factorial(3)
## [1] 6
sample(x = die, size = 1)
## [1] 4
args(round)
## function (x, digits = 0) 
## NULL
# die with replacement
sample(die, size = 2, replace = TRUE)
## [1] 4 6

2 Creating Functions

roll <- function() {
  die <- 1:6
  dice <- sample(die, size = 2, replace = TRUE)
  sum(dice)
}

roll()
## [1] 6
# to see what's the code of a function:
roll
## function() {
##   die <- 1:6
##   dice <- sample(die, size = 2, replace = TRUE)
##   sum(dice)
## }
# calling a name in the function which does not exist results in an error:
roll2 <- function() {
  dice <- sample(bones, size = 2, replace = TRUE)
  sum(dice)
}
roll2()
## Error in sample(bones, size = 2, replace = TRUE): object 'bones' not found
# to get around the problem, make the name an argument of the function:

roll2 <- function(bones) {
  dice <- sample(bones, size = 2, replace = TRUE)
  sum(dice)
}

# I just now need to supply "bones" when I call this function:
roll2(bones = 1:4)
## [1] 3
roll2(bones = 1:6)
## [1] 11
roll2()
## Error in sample(bones, size = 2, replace = TRUE): argument "bones" is missing, with no default
# I can assign a default value for "bones":
roll2 <- function(bones = 1:6) {
  dice <- sample(bones, size = 2, replace = TRUE)
  sum(dice)
}