Chap 8 Function

1. sprintf()

This function is equivalent to f-string in Python and printf in C, with %s represents string and %d represents integer. Here the function in R is more alike to the format in C rather than Python, you have to be aware of the {}

do.hello <- function(name, year){
    sprintf("Hello %s, You are %d years old.", name, year)
}

do.hello("Dean", 24)
## [1] "Hello Dean, You are 24 years old."

2. Extra parameters

In R, it is acceptable to add another parameter in functions

double.num <- function(num, double=2, ...){
    return(num * double)
}

double.num(3, double=2, 7) # You can see that 7 is accepted and will not raise error 
## [1] 6

3. do.call

# Parameters in do.call()
# do.call(function, arguments, quote = FALSE, envir = parent.frame())
run.this <- function(data, func=mean){
    do.call(func, args = list(data)) # args receive list type variable
}

run.this(c(1:10), sd)
## [1] 3.02765

Chap 9 Process Control

1. switch()

This function is same as switch() in C, it seems like a hash table, which one parameter corresponds to one action or output

use.switch <- function(x){
    switch (x,
        '1' = 'first',
        '2' = 'second',
        '3' = 'third',
        '4' = 'fourth',
        'other'
    )
}

use.switch('1')
## [1] "first"
use.switch(4)
## [1] "fourth"
use.switch(5)
## [1] "other"
use.switch(6) # it is null
is.null(use.switch(6))
## [1] TRUE

2. ifelse()

# ifelse(test, yes, no)
vec <- c(1, 1, 2, 3, 5, 6, 7, 1, NA, 1, 0, NA, NA)
vec_1 <- ifelse(is.na(vec), -1, ifelse(vec >= 3, 1, 0)) # here I loop ifelse() which could divide vector into 3 groups (NA, value >= 3, and value < 3)
# We should see the output be (0, 0, 0, 1, 1, 1, 1, 0, -1, 0, 0, -1, -1)
vec_1
##  [1]  0  0  0  1  1  1  1  0 -1  0  0 -1 -1
# Notice that whether the data has missing or not, the ifelse function would regard NA as NA value if it does not match the condition!!!
vec_2 <- ifelse(vec >= 3, 1, 0)
vec_2
##  [1]  0  0  0  1  1  1  1  0 NA  0  0 NA NA

Chap 10 Loop

1. For loop

The for loop format is much the same as C and C++

for (i in 1:10) {
    print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10

2. Loop enforcement

Use next and break to enforce the loop process

# 'next' is equal to 'continue' and break is same in Python
for (i in 1:10){
    if (i == 3)
        next
    if (i == 7)
        break
    print(i)
}
## [1] 1
## [1] 2
## [1] 4
## [1] 5
## [1] 6