Simple expression

2 + 3
3 - 6
18 * 2
## [1] 5
## [1] -3
## [1] 36

Devide integers and you will get a floating-point number

9 / 4
## [1] 2.25

And use “%/%” to get integer result

9 %/% 4
## [1] 2

“^” and “**” are used as exponentiation operators

2 ^ 3
2 ** 3
## [1] 8
## [1] 8

Assignments

We use arrow operator to assign a value to a variable, for example:

x <- 19

It works in reverse direction

19 -> x

Put the assignment in parentheses to print it

(x <- "HDPE là ngon luôn")
## [1] "HDPE là ngon luôn"

Length of vector and length of string

#length() is used to give length of a vector 
length("HDPE là ngon luôn")
## [1] 1
#if we want to know the length of a string, we must use nchar() 
nchar("muối bỏ biển")
## [1] 12

Index

R has several differences compared to other languages that index starts from 0 to n-1, index in R goes from 1 to n instead Using : operator or c() to extract a subvector:

#
HDPE <- 1:6
HDPE[3:6]
## [1] 3 4 5 6
HDPE[c(1, 4, 6)]
## [1] 1 4 6

Combine with expressions to pick values that match with expressions’ result

HDPE <- 1:6
HDPE[HDPE %% 2 == 1]
## [1] 1 3 5

Name the vector indices and use those to index the vector

HDPE <- c("muối" = 1, "bỏ" = 2, "biển" = 3)
HDPE
## muối   bỏ biển 
##    1    2    3

Or do it by using names():

names(HDPE) <- c("là", "ngon", "luôn")
HDPE
##   là ngon luôn 
##    1    2    3

Vectorized Expressions

phai_chiu <- 1:5
phai_chiu ** 2
## [1]  1  4  9 16 25

Use operators with vectors that have the same length or not

phai_chiu <- 6:10
lam_duoc_gi_pha_day <- 1:5
lo_roi_cac_chau_oi <- 1:3
phai_chiu - lam_duoc_gi_pha_day
## [1] 5 5 5 5 5
phai_chiu - lo_roi_cac_chau_oi
## Warning in phai_chiu - lo_roi_cac_chau_oi: longer object length is not a
## multiple of shorter object length
## [1] 5 5 5 8 8

Functions

sum_of_xy <- function(x, y){
  return (x + y);
}
sum_of_xy(2, 4)
## [1] 6

Control structures

HDPE <- 1:5
if (sum(HDPE) > 10){
  print("Là ngon luôn");
}else{
  print("Như muối bỏ biển");
}
## [1] "Là ngon luôn"

for and while loop

x = 1:5
for (x_temp in x){
  print(x_temp * 2)
}
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
index = 1
while (index <= length(x)){
  x[index] = x[index] - 10
  index = index + 1
}
x
## [1] -9 -8 -7 -6 -5

Factors

To categorize data

HDPE <- factor(c("bỏ", "muối", "bỏ", "biển", "muối", "biển"), levels = c("muối", "bỏ", "biển"))
ordered(HDPE)
## [1] bỏ   muối bỏ   biển muối biển
## Levels: muối < bỏ < biển