Paste string

# has a space between A and B
paste("A", "B")
## [1] "A B"
# no spaces
paste0("A", "B")
## [1] "AB"
str = "C"
# append A to the beginning
str = paste0("A", str)
str
## [1] "AC"
# append B to the end
str = paste0(str, "B")
str
## [1] "ACB"

If else

x = "A"
if (x == "A") {
  print(x)
} else if (x == "B") {
  print(x)
} else {
  stop("Err : x must be either A or B !")
}
## [1] "A"

Inline ifelse

match = 1
mismatch = -1
# if TRUE then match
s = ifelse(TRUE, match, mismatch)
print(s)
## [1] 1
# else mismatch
s = ifelse(FALSE, match, mismatch)
print(s)
## [1] -1

Get matrix value by row/col name

S = matrix(c(2, 1, -2, 0), nrow = 2)
rownames(S) <- c("A","B")
colnames(S) <- c("C","D")
print(S)
##   C  D
## A 2 -2
## B 1  0
# by index
print(S[1,2])
## [1] -2
# by name
print(S["A","D"])
## [1] -2
# assign value
S[1,2] = 3
print(S[1,2])
## [1] 3

For loop

for (i in 1:3) {
  cat("i = ", i ,"\n")
}
## i =  1 
## i =  2 
## i =  3
for (i in 1:3) {
  for (j in 1:3) {
    cat("i = ", i ,", j = ", j ,"\n")
  }
}
## i =  1 , j =  1 
## i =  1 , j =  2 
## i =  1 , j =  3 
## i =  2 , j =  1 
## i =  2 , j =  2 
## i =  2 , j =  3 
## i =  3 , j =  1 
## i =  3 , j =  2 
## i =  3 , j =  3

Math

max(1,2)
## [1] 2
max(1,2,3)
## [1] 3
F = matrix(c(1,1,2,1, 1,1,1,2, 1,2,1,1), nrow = 3)
F
##      [,1] [,2] [,3] [,4]
## [1,]    1    1    1    2
## [2,]    1    1    2    1
## [3,]    2    1    1    1
max_score = max(F)
# max_i, max_j are the coordinate of the highest score max_score in F matrix. 
co = which(F==max_score, arr.ind=TRUE)
co
##      row col
## [1,]   3   1
## [2,]   2   3
## [3,]   1   4
max_i = co[nrow(co),1]  
max_j = co[nrow(co),2]
#[2,3] is rightmost position 
paste(max_i, max_j)
## [1] "1 4"
F = matrix(c(1,1,2,1, 1,1,1,2, 1,2,1,2), nrow = 3)
F
##      [,1] [,2] [,3] [,4]
## [1,]    1    1    1    2
## [2,]    1    1    2    1
## [3,]    2    1    1    2
max_score = max(F)
# max_i, max_j are the coordinate of the highest score max_score in F matrix. 
co = which(F==max_score, arr.ind=TRUE)
co
##      row col
## [1,]   3   1
## [2,]   2   3
## [3,]   1   4
## [4,]   3   4
max_i = co[nrow(co),1]  
max_j = co[nrow(co),2]
#[2,3] is rightmost position 
paste(max_i, max_j)
## [1] "3 4"