1.What is R

là một ngôn ngữ lập trình phổ biến được sử dụng để tính toán thống kê và trình bày đồ họa. Công dụng phổ biến nhất của nó là phân tích và trực quan hóa dữ liệu.

#phân tích dữ liệu

#trực quan hóa dữ liệu

#khoa học dữ liệu và học máy

#cung cấp nhiều kỹ thuật thống kê (chẳng hạn như kiểm tra thống kê, phân loại, phân cụm và giảm dữ liệu)

#vẽ đồ thị bằng R, như biểu đồ hình tròn, biểu đồ, biểu đồ hộp, biểu đồ phân tán,v.v.. 

#hoạt động trên các nền tảng khác nhau (Windows, Mac, Linux) 

#là mã nguồn mở và miễn phí

#có sự hỗ trợ cộng đồng lớn

#có nhiều gói (thư viện hàm) có thể được sử dụng để giải quyết các vấn đề khác nhau

2.R Syntax

"Hello world!"
## [1] "Hello world!"
5 + 4
## [1] 9

3.R Print Output

print("hello")
## [1] "hello"
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

4.R Comments

# This is a comment
"Hello World!"
## [1] "Hello World!"

5.R Variables

Variables

age <- 40
name <- "vnq"

age
## [1] 40
name
## [1] "vnq"
print(name)
## [1] "vnq"

R Concatenate Elements (nối các phần tử)

text <- "hello"
paste(text, "world")
## [1] "hello world"
name <- "vnq"
paste(text, name)
## [1] "hello vnq"

R Multiple Variables

var1 <- var2 <- var3 <- 3
var1
## [1] 3
var2
## [1] 3
var3
## [1] 3

6.R Data Types

# numeric
x <- 10.5
class(x)
## [1] "numeric"
y <- 10
class(y)
## [1] "numeric"
# integer
x <- 1000L
class(x)
## [1] "integer"
# complex
x <- 9i + 3
class(x)
## [1] "complex"
# character/string
x <- "R is exciting"
class(x)
## [1] "character"
# logical
x <- TRUE
class(x)
## [1] "logical"

7.Numbers

There are three number types in R:

x <- 1
y <- 1L
z <- 5i + 1

x
## [1] 1
class(x)
## [1] "numeric"
y
## [1] 1
class(y)
## [1] "integer"
z
## [1] 1+5i
class(z)
## [1] "complex"

Type Conversion (chuyển đổi kiểu) You can convert from one type to another with the following functions:

x <- 3L
y <- 4

class(x)
## [1] "integer"
a <- as.numeric(x)
class(a)
## [1] "numeric"
class(y)
## [1] "numeric"
b <- as.integer(y)
class(b)
## [1] "integer"

8.R Math

Built-in Math Functions R also has many built-in math functions that allows you to perform mathematical tasks on numbers.

For example, the min() and max() functions can be used to find the lowest or highest number in a set:

6 + 4
## [1] 10
max(1,10,8)
## [1] 10
min(2,7,9)
## [1] 2

sqrt() The sqrt() function returns the square root of a number:

sqrt(2)
## [1] 1.414214

abs() The abs() function returns the absolute (positive) value of a number:

abs(-5)
## [1] 5

The ceiling() function rounds a number upwards to its nearest integer, and the floor() function rounds a number downwards to its nearest integer, and returns the result:

ceiling(4.4)
## [1] 5
floor(4.4)
## [1] 4

9.R Strings

str <- "hello"
str
## [1] "hello"

Multiline Strings You can assign a multiline string to a variable like this:

str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

# dùng cat() is so peak
cat(str)
## Lorem ipsum dolor sit amet,
## consectetur adipiscing elit
## sed do eiusmod tempor incididunt
## ut labore et dolore magna aliqua.
str # print the value of str
## [1] "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua."

đếm kí tự String Length dùng nchar()

str <- "hello world"
nchar(str)
## [1] 11

Check a String dùng grepl() để kiểm tra xem có kí tự hay chuỗi kí tự có trong chuỗi ko

str <- "hello world"
grepl("hello", str)
## [1] TRUE

R Escape Characters

str <- "hello world\"viking\"hello"
cat(str)
## hello world"viking"hello

10.R Booleans / Logical Values

10 == 9
## [1] FALSE
10 == 10
## [1] TRUE
10 > 9
## [1] TRUE
10 < 9
## [1] FALSE

You can also compare two variables:

a <- 10
b <- 9
a > b
## [1] TRUE

kết hợp với if else:

a <- 18
b <- 20
if (b > a) {
  print ("b is greater than a")
} else {
  print("b is not greater than a")
}
## [1] "b is greater than a"

11.R If … Else

if (20 > 19){
  print("D")
}else{
  print("S")
}
## [1] "D"

Elseif

a <- 20
b <- 22
if (a > b){
  print("S")
}else if(b > a){
  print("D")
}else{
  print("S")
}
## [1] "D"

Nested If Statements

x <- 20
if (x > 10){
  print(x)
  if(x == 20){
    print(x * 2)
  }
}
## [1] 20
## [1] 40
x <- 41

if (x > 10) {
  print("Above ten")
  if (x > 20) {
    print("and also above 20!")
  } else {
    print("but not above 20.")
  }
} else {
  print("below 10.")
}
## [1] "Above ten"
## [1] "and also above 20!"

AND

a <- 20
b <- 50
c <- 30

if (a < b & c < b){
  print("AND")
}
## [1] "AND"

OR

a <- 20
b <- 50
c <- 30

if (a > b | b > c){
  print("OR")
}
## [1] "OR"

12.R While Loop

i <- 1
while(i <= 6){
  print(i)
  i <- i + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6

Break

i <- 1
while(i <= 6){
  if(i == 4){
    break
  }
  print(i)
  i <- i + 1
}
## [1] 1
## [1] 2
## [1] 3

Next

i <- 0
while (i < 6) {
  i <- i + 1
  if (i == 3) {
    next
  }
  print(i)
}
## [1] 1
## [1] 2
## [1] 4
## [1] 5
## [1] 6
dice <- 1
while (dice <= 6) {
  if (dice < 6) {
    print("No Yahtzee")
  } else {
    print("Yahtzee!")
  }
  dice <- dice + 1
}
## [1] "No Yahtzee"
## [1] "No Yahtzee"
## [1] "No Yahtzee"
## [1] "No Yahtzee"
## [1] "No Yahtzee"
## [1] "Yahtzee!"

13.For Loops

vecto

x <- c(1,2,3)
for (i in x){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
class(x)
## [1] "numeric"

list

lst <- list("hello", "world", "con j the")

for (i in lst){
  print(i)
}
## [1] "hello"
## [1] "world"
## [1] "con j the"
class(lst)
## [1] "list"

next

x <- list("kid", "me too", "lulu")
for (i in x){
  if (i == "me too"){
    next
  }
  print(i)
}
## [1] "kid"
## [1] "lulu"

break

x <- list("kid", "me too", "lulu")
for (i in x){
  if (i == "me too"){
    break
  }
  print(i)
}
## [1] "kid"

R Nested Loops

adj <- list("hoa", "big", "tasty")

fruits <- list("apple", "banana", "cherry")

for (i in adj){
  for (y in fruits){
    print(paste(i, y))
  }
}
## [1] "hoa apple"
## [1] "hoa banana"
## [1] "hoa cherry"
## [1] "big apple"
## [1] "big banana"
## [1] "big cherry"
## [1] "tasty apple"
## [1] "tasty banana"
## [1] "tasty cherry"

14.R Functions

my_fun <- function(){
  print("hello world")
}

my_fun()
## [1] "hello world"
my_fun <- function(fname){
  paste("hello", fname)
}

my_fun("quy")
## [1] "hello quy"

Return Values

my_fun <- function(a, b){
  tong <- a + b
  return (tong)
}
my_fun(4, 5)
## [1] 9

R Nested Functions

fun_name <- function(){
  fun_son <- function(x, y){
    return (x + y)
  }
  
  fun_son(4, 3)
}

fun_name()
## [1] 7
Outer_func <- function(x) {
  Inner_func <- function(y) {
    a <- x + y
    return(a)
  } 
  return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5)
## [1] 8

R Function Recursion

fun_n <- function(k){
  fun_test <- function(k){
    if (k > 0){
      return (k + fun_test(k -  1))
    }else{
      return (0)
    }
  }
  fun_test(k)
}

x <- fun_n(5)
x
## [1] 15

Global Variables

c <- 4
fun_n <- function(){
  c <- 5
  print(c)
}
c
## [1] 4
fun_n()
## [1] 5
c
## [1] 4

15.R Data Structures

vecto thì đồng nhất kiểu dữ liệu list thì không đồng nhất kiểu dữ liệu

Data Structures -Vectors access element use v[]

fruits <- c("banana", "apple", "orange")

# Print fruits
fruits[1]
## [1] "banana"
fruits
## [1] "banana" "apple"  "orange"

-Lists access element use l[[]]

thislist <- list("apple", "banana", 50, 100)

# Print the list
thislist[[2]]
## [1] "banana"
thislist
## [[1]]
## [1] "apple"
## 
## [[2]]
## [1] "banana"
## 
## [[3]]
## [1] 50
## 
## [[4]]
## [1] 100

-Matrices access element use matran[?, ?]

my_matrix = matrix(1:6, nrow = 3, ncol = 2)
my_matrix[1, 2]
## [1] 4
my_matrix
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6
my_matrix[2, 2]
## [1] 5
my_matrix[, 2] #access all ncol
## [1] 4 5 6
my_matrix[2, ]
## [1] 2 5

-Arrays

my_array <- array(1:24, dim = c(4,2,3)) #c(n_row, n_col, n_lớp)
my_array
## , , 1
## 
##      [,1] [,2]
## [1,]    1    5
## [2,]    2    6
## [3,]    3    7
## [4,]    4    8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    9   13
## [2,]   10   14
## [3,]   11   15
## [4,]   12   16
## 
## , , 3
## 
##      [,1] [,2]
## [1,]   17   21
## [2,]   18   22
## [3,]   19   23
## [4,]   20   24

-Data Frames

id <- 1:3
name <- c("quy", "ngoc", "vu")
class <- c(12, 11, 10)
my_data <- data.frame(id, name, class)
my_data
##   id name class
## 1  1  quy    12
## 2  2 ngoc    11
## 3  3   vu    10