#Phần 1 : Lập trình python cơ bản ##Tạo vector sử dụng hàm rep và seq
#1
seq(from = 1, to = 20, by = 1)
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#2
seq(from = 20, to = 1, by = -1)
## [1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
#3
c(seq(1, 20), seq(19, 1, -1))
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 19 18 17 16 15
## [26] 14 13 12 11 10 9 8 7 6 5 4 3 2 1
#4
vec_e <- rep(c(4,6,3), times = 10)
vec_e
## [1] 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3
vec_f <- c(rep(4, 11), rep(c(6, 3), 10))
vec_f
## [1] 4 4 4 4 4 4 4 4 4 4 4 6 3 6 3 6 3 6 3 6 3 6 3 6 3 6 3 6 3 6 3
#Phần 2 : Lập trình hàm trong R Sử dụng lập trình hàm trong R để làm các bài toán sau: Nhập vào một véc tơ myvector gồm có n số hạng nguyên. Hãy viết: # Hàm tính tổng, giá trị trung bình các phần tử của myvector # Hàm tính giá trị nhỏ nhất, lớn nhất của myvector # Hàm tính giá trị phương sai và độ lệch chuẩn của myvector
# Hàm tính tổng
n <- as.integer(readline("n: "))
## n:
myvector <- scan(n=n)
myvector
## numeric(0)
sumF <- function(myvector){
sum <- 0
for (i in 1:length(myvector)) {
sum <- sum + myvector[i]
}
return(sum)
}
ans_sum<-sumF(myvector)
ans_sum
## numeric(0)
#Hàm tính trung bình
avgF <- function(myvector){
avg <- ans_sum/length(myvector)
return (avg)
}
avgF(myvector)
## numeric(0)
#Hàm tính max
maxF <- function(myvector){
max_v = -9999
for (i in 1:length(myvector)) {
if(myvector[i]> max_v)
max_v = myvector[i]
}
return(max_v)
}
#Hàm tính min
minF <- function(myvector){
min_v = 9999
for (i in 1:length(myvector)) {
if(myvector[i]< min_v)
min_v = myvector[i]
}
return(min_v)
}
#Phần 3 : Tính Phương sai
#hàm tính hiệp phương sai với 2 vector x và y:
covariance = function(x,y){
a = (x-mean(x))*(y-mean(y))
sum = 0
if(length(x)==length(y)){
for(i in 1:length(x)){
sum = sum + a[i]
}
}
return(sum/(length(x)-1))
}
x = c(1,2,3,7,4,6,9,-5)
y = c(2,3,6,7,1,-6,6,2)
covariance(x,y)
## [1] 2.303571
#Phần 4 : Trực quan DL
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.2
library(gapminder)
## Warning: package 'gapminder' was built under R version 4.2.2
mydata <- gapminder
head(gapminder)
## # A tibble: 6 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
##Lớp biến số về định nghĩa thì lớp này có 2 biến là x và y. Nếu chúng ta muốn thể hiện mối liên quan giữa giới tính và thu nhập thì thông thường x sẽ là biến giới tính và y là biến thu nhập.
p=ggplot(data=gapminder,aes(x=gdpPercap,y=lifeExp))
p + geom_point(aes(color = continent))
##Khoảng cách giữa giá trị trục tung và trục hoành
p1 = ggplot(data=gapminder,aes(x=gdpPercap,y=lifeExp)) + geom_point(aes(color = continent))
p1 <- p1 + scale_x_log10() + geom_smooth(method="loess")
p1
## `geom_smooth()` using formula = 'y ~ x'
##Thực hành về ggplot2
mydata <- gapminder
head(gapminder)
## # A tibble: 6 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
str(gapminder)
## tibble [1,704 × 6] (S3: tbl_df/tbl/data.frame)
## $ country : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ year : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
## $ lifeExp : num [1:1704] 28.8 30.3 32 34 36.1 ...
## $ pop : int [1:1704] 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
## $ gdpPercap: num [1:1704] 779 821 853 836 740 ...
###Trực quan dữ liệu
p2 <- ggplot(data = mydata, mapping = aes(x = gdpPercap, y = lifeExp))
p2 + geom_point() -> p2
#Thêm đường biểu diễn tương quan
p2 + geom_smooth(method = "loess") -> p2
#Trực quan dữ liệu biến lục địa
ggplot(data = mydata, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(aes(color = continent)) +
geom_smooth(method = "loess")
## `geom_smooth()` using formula = 'y ~ x'
#Chuyển qua đơn vị log() cho 好看
ggplot(data = mydata, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(aes(color = continent)) +
geom_smooth(method = "loess") +
scale_x_log10()
## `geom_smooth()` using formula = 'y ~ x'
##Gán nhãn cho các biểu đồ
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 4.2.2
ggplot(data = mydata, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(aes(color = continent)) +
geom_smooth(method = "loess") +
scale_x_log10() +
labs(x =" Log GDP per Capita", y = "Life Expectancy") +
ggtitle("Association between GDP Per Capita and Life Expectancy") + theme(plot.title = element_text(lineheight = 0.8, face = "bold", hjust = 0.5)) + theme_economist()
## `geom_smooth()` using formula = 'y ~ x'
##Biểu đồ phổ biến hay được sử dụng trong ggplot2
year2007 <- subset(mydata, year == 2007)
head(year2007)
## # A tibble: 6 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 2007 43.8 31889923 975.
## 2 Albania Europe 2007 76.4 3600523 5937.
## 3 Algeria Africa 2007 72.3 33333216 6223.
## 4 Angola Africa 2007 42.7 12420476 4797.
## 5 Argentina Americas 2007 75.3 40301927 12779.
## 6 Australia Oceania 2007 81.2 20434176 34435.
###Histogram
ggplot(data = year2007, mapping = aes(gdpPercap)) +
geom_histogram(fill = "pink", color = "white") +
labs(title = "Phân bổ GDP bình quân đầu người năm 2007")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Nếu ta không muốn Oy là count mà muốn là tần suất xuất hiện thì ta làm
như sau :
ggplot(data = year2007, mapping = aes(gdpPercap)) + geom_histogram(aes(y = ..density..), fill = "red", color = "white")
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Ví dụ : biểu đồ phân phối theo hình lục địa
ggplot(data = year2007, mapping = aes(gdpPercap, fill = continent)) + geom_density(alpha = 0.4)
###Biểu đồ thanh (Barplot)
#Xoá bớt dl thừa
dim(year2007)
## [1] 142 6
#Barplot
ggplot(data = year2007, mapping = aes(x = continent, fill = continent)) + geom_bar() + theme(legend.position = "none")
###Sử dụng toán tử điều kiện [] để tạo ra một biến mới tên là level_age
có tính thứ bậc
year2007$level_age[year2007$lifeExp < 60.0] <- "< 60 age"
## Warning: Unknown or uninitialised column: `level_age`.
year2007$level_age[60.0 <= year2007$lifeExp & year2007$lifeExp <= 80.0] <- "60-80 age"
year2007$level_age[year2007$lifeExp > 80.0] <- "> 80 age"
ggplot(data = year2007, aes(x = continent, fill = level_age)) +
geom_bar()
#### Biểu đồ barplot có thể miêu tả 1 biến liên tục Ví dụ: Chúng ta muốn
thể hiện tuổi thọ trung bình của mỗi quốc gia thuộc Châu Á (Asian).
Trước tiên cần lọc các quốc gia có lục địa là Asian:
asia <- subset(mydata, year == 2007 & continent == "Asia")
dim(asia)
## [1] 33 6
Từ đó ta thấy Châu Á có 33 quốc gia.
ggplot(data = asia, mapping = aes(x = country, y = lifeExp, fill = country)) + geom_bar(stat = "identity", width = 0.9)
Ta có thể đảo ngược biểu đồ để cho dễ nhìn hơn như sau :
ggplot(data = asia, mapping = aes(x = country, y = lifeExp, fill = country)) + geom_bar(stat = "identity", width = 0.9) + coord_flip()
Biểu đồ này rất khó so sánh, chúng ta nên sắp xếp lại theo trật tự
ggplot(data = asia, mapping = aes(x = reorder(country, lifeExp), y = lifeExp, fill = country)) + geom_bar(stat = "identity", width = 0.9) + coord_flip() + theme(legend.position = "none") + labs(x="", y="Life Expectancy") -> graph1
###Biểu đồ hộp (Boxplot) Giả sử chúng ta muốn tóm tắt thu nhập bình quân năm 2007 của 142 quốc gia bằng biểu đồ hộp
ggplot(data = year2007, aes(x = continent, y = gdpPercap, fill = continent)) + geom_boxplot(alpha = 0.5)
ggplot(data = year2007, aes(x = continent, y = gdpPercap, fill = continent)) + geom_boxplot(alpha = 0.6) + geom_jitter(alpha = 0.9)