Bài Tập 1

a, kiểm tra xem \(A^3 = 0\)

matrixA = matrix(c(1,1,3,5,2,6,-2,-1,-3), byrow = T, nrow = 3)
matrix0 = matrix(rep(0, 9), nrow = 3)

all((matrixA%*% matrixA%*%matrixA)== matrix0) 
## [1] TRUE

b, thay thế cột thứ 3 của ma trận A bằng tổng của cột thứ 1 và cột thứ 2 của ma trận A

A = matrix(c(1,1,3,5,2,6,-2,-1,-3), byrow = T, nrow = 3)
A[,3] = A[,1]+A[,2]
A
##      [,1] [,2] [,3]
## [1,]    1    1    2
## [2,]    5    2    7
## [3,]   -2   -1   -3

Bài tập 2

hàm outer được sử dụng nhiều để tạo ra ma trận khác nhau theo một quy luật nào đó.

A <-  0:4
print(outer(A,A,FUN = "+"))
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    0    1    2    3    4
## [2,]    1    2    3    4    5
## [3,]    2    3    4    5    6
## [4,]    3    4    5    6    7
## [5,]    4    5    6    7    8

Bài tập 3

row1 = c(1,2,3,4,5)
row2 = c(2,1,2,3,4)
row3 = c(3,2,1,2,3)
row4 = c(4,3,2,1,2)
row5 = c(5,4,3,2,1)

matrixA = matrix(c(row1,row2,row3,row4,row5), nrow = 5)

matrixB = c(7,-1,-3,5,17)

matrix_X = solve(matrixA, matrixB)
matrix_X
## [1] -2  3  5  2 -4

Bài tập 4:

i <-  1:20
j <- 1:5

sum(i^4*(1/sum((j+3))))
## [1] 24088.87

Bài tập 5:

library(gapminder)
data(gapminder)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# 1. lọc dữ liệu dành cho việt nam và đặt tên tập dữ liệu là vietnamdata

vietnamdata <- gapminder %>%
  filter(country == "Vietnam")
vietnamdata
## # A tibble: 12 × 6
##    country continent  year lifeExp      pop gdpPercap
##    <fct>   <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Vietnam Asia       1952    40.4 26246839      605.
##  2 Vietnam Asia       1957    42.9 28998543      676.
##  3 Vietnam Asia       1962    45.4 33796140      772.
##  4 Vietnam Asia       1967    47.8 39463910      637.
##  5 Vietnam Asia       1972    50.3 44655014      700.
##  6 Vietnam Asia       1977    55.8 50533506      714.
##  7 Vietnam Asia       1982    58.8 56142181      707.
##  8 Vietnam Asia       1987    62.8 62826491      821.
##  9 Vietnam Asia       1992    67.7 69940728      989.
## 10 Vietnam Asia       1997    70.7 76048996     1386.
## 11 Vietnam Asia       2002    73.0 80908147     1764.
## 12 Vietnam Asia       2007    74.2 85262356     2442.
# 2. sử dụng thư viện dplyr và toán tử pipe 
# cho biết tuổi thọ trung bình của người việt nam

vietnamdata %>% 
  mutate(mean_age = mean(lifeExp, na.rm=T)) %>%
  select(mean_age, mean_age)
## # A tibble: 12 × 1
##    mean_age
##       <dbl>
##  1     57.5
##  2     57.5
##  3     57.5
##  4     57.5
##  5     57.5
##  6     57.5
##  7     57.5
##  8     57.5
##  9     57.5
## 10     57.5
## 11     57.5
## 12     57.5
# 3, sử dụng biểu đồ cột, thư viện ggplot2, thư viện gridExtran
library(ggplot2)
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
## 
##     combine
gapminder2007 <- gapminder %>%
  filter(year == 2007)

Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia") %>%
  mutate(total = gdpPercap * pop)

Europe2007 <- gapminder2007 %>%
  filter(continent == "Europe")%>%
  mutate(total = gdpPercap * pop)

graph1 <- ggplot(data = Asia2007, mapping = aes(x = reorder(country, -total), y = total, fill = country))+
  geom_bar(stat = "identity")+
  coord_flip()+
  theme(legend.position = "none")+
  labs(y = "Total GDP of each Country on Asia",
       x = "Country")
graph1

graph2 <- ggplot(data = Europe2007, mapping = aes(x = reorder(country, -total), y = total, fill = country))+
  geom_bar(stat = "identity")+
  coord_flip()+
  theme(legend.position = "none")+
  labs(y = "Total GDP of each Country on Europe",
     x = "Country")
graph2

grid.arrange(graph1,graph2, nrow = 1)

Bài 6

library(gapminder)
if(!require(gapminder)){
  install.packages("gapminder")
  library(gapminder)
}
# cho biết trong tập dữ liệu có những cột nào
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 ...
# table kiểm tra dữ liệu có đầy đủ không?
table(gapminder$continent, gapminder$year)
##           
##            1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
##   Africa     52   52   52   52   52   52   52   52   52   52   52   52
##   Americas   25   25   25   25   25   25   25   25   25   25   25   25
##   Asia       33   33   33   33   33   33   33   33   33   33   33   33
##   Europe     30   30   30   30   30   30   30   30   30   30   30   30
##   Oceania     2    2    2    2    2    2    2    2    2    2    2    2

vì table() không có đối số data nên ta phải chỉ định tên biến.

chúng ta sử dụng with() để thay thế cho table()

with(gapminder, {table(continent, year)})
##           year
## continent  1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
##   Africa     52   52   52   52   52   52   52   52   52   52   52   52
##   Americas   25   25   25   25   25   25   25   25   25   25   25   25
##   Asia       33   33   33   33   33   33   33   33   33   33   33   33
##   Europe     30   30   30   30   30   30   30   30   30   30   30   30
##   Oceania     2    2    2    2    2    2    2    2    2    2    2    2

1. Biểu đồ 1D: Biểu đồ Bar cho biến rời rạc

library(ggplot2)
ggplot(gapminder, mapping = aes(x = continent))+
  geom_bar()

Thêm màu sắc cho mỗi cột, ánh xạ thuộc tính fill tới continent

a, ánh xạ trong

khi thao tác sẽ ảnh hưởng đến dữ liệu

# ánh xạ trong 
ggplot(gapminder, mapping = aes(x = continent, fill = continent))+
  geom_bar()

b, ánh xạ ngoài

khi thao tác không ảnh hưởng đến dữ liệu

ggplot(gapminder, mapping = aes(x = continent))+
  geom_bar(aes(fill = continent))

Hàm ..count.. đếm số lượng quan sát trong từng nhóm dữ liệu

ggplot(gapminder, aes(x =continent,y = ..count../12, fill = continent))+
  geom_bar()
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# ẩn legend
ggplot(gapminder, mapping = aes(x = continent, y = ..count../12, fill = continent))+
  geom_bar()+
  #guides(fill = F)
  theme(legend.position = "none")

để lưu ggplot vừa tạo vào một biến

mybar <- last_plot()
# hoặc gắn trực tiếp vào ggplot

thêm các lớp khác hoặc chuyển đổi tọa độ bằng các hàm coord_.

+, coord_trans(y=“sqrt”): vẽ các tần số theo thang căn bậc 2

+, coord_flip(): hoán đổi trục X,Y để tạo biểu đồ ngang

+, coord_polar(): ánh xạ X,Y tới tọa độ cực (bán kính, góc): biểu đồ coxcomb chứ không phải biểu đồ tròn

mybar+coord_trans(y="sqrt")

mybar + coord_flip()

mybar+coord_polar()

2. Đồ thị 1D: Đồ thị mật độ cho các biến liên tục

ggplot(gapminder, aes(x = lifeExp))+
  geom_density()

ggplot(gapminder ,aes(x = lifeExp))+
  geom_density(size = 1.5, fill = "pink", alpha = 0.3)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# xếp thêm một biểu đồ khác

ggplot(gapminder, aes(x = lifeExp))+
  geom_density(size = 1.5, fill = "pink", alpha = 0.5)+
  geom_histogram(aes(y = ..density..), binwidth = 4, color = "black", fill = "lightblue", alpha = 0.5)

ggplot(gapminder, aes(x = lifeExp, fill = continent))+
  geom_density(alpha = 0.3)

Sơ đồ hộp và cac tóm tắt trực quan khác

gap1 <- ggplot(gapminder, aes(x = continent, y = lifeExp, fill = continent))
# thêm lớp boxplott
gap1+geom_boxplot(outlier.size = 2)

# xóa chú giải
gap1+geom_boxplot(outlier.size = 2)+
  guides(fill = F)
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# vẽ đồ thị theo chiều ngang
ggplot(gapminder, aes(x = lifeExp, y = continent, fill = continent))+
  geom_boxplot(outlier.size = 2)

# vẽ geom_violin()
ggplot(gapminder, aes(x = continent, y = lifeExp, fill = continent))+
  geom_violin()

ggplot(gapminder, aes(x = gdpPercap))+
  geom_density()

ggplot(gapminder, aes(x = continent))+
  geom_density()

# thay x = log10(gdpPercap)

ggplot(gapminder, aes(x = log10(gdpPercap), fill = continent))+
  geom_density()

# tạo boxplot của gdpPercap như continent

ggplot(gapminder, aes(x = gdpPercap, fill = continent))+
  geom_boxplot()

3. Biểu đồ chuỗi thời gian

ggplot(gapminder, aes(x = year, y = lifeExp, group = country))+
  geom_line()

gapminder %>%
  group_by(country) %>%
  summarise(sd = sd(lifeExp), IQR = IQR(lifeExp)) %>%
  top_n(8) %>%
  arrange(desc(sd))
## Selecting by IQR
## # A tibble: 8 × 3
##   country               sd   IQR
##   <fct>              <dbl> <dbl>
## 1 Oman                14.1  25.5
## 2 Vietnam             12.2  21.2
## 3 Saudi Arabia        11.9  20.3
## 4 Indonesia           11.5  18.4
## 5 Libya               11.4  19.8
## 6 Yemen, Rep.         11.0  19.7
## 7 West Bank and Gaza  11.0  19.3
## 8 Tunisia             10.7  19.1
gapminder %>% 
  group_by(continent, year) %>%
  summarise(lifeExp= median(lifeExp)) %>%  head()
## `summarise()` has grouped output by 'continent'. You can override using the
## `.groups` argument.
## # A tibble: 6 × 3
## # Groups:   continent [1]
##   continent  year lifeExp
##   <fct>     <int>   <dbl>
## 1 Africa     1952    38.8
## 2 Africa     1957    40.6
## 3 Africa     1962    42.6
## 4 Africa     1967    44.7
## 5 Africa     1972    47.0
## 6 Africa     1977    49.3
gapminder %>% 
  group_by(continent, year) %>%
  summarise(lifeExp= median(lifeExp)) %>%  
  ggplot(aes(x = year, y = lifeExp, color = continent))+
  geom_line(size=1)+
  geom_point(size = 1.5) -> gapyear
## `summarise()` has grouped output by 'continent'. You can override using the
## `.groups` argument.
gapyear

gapminder %>% 
  group_by(continent, year) %>%
  summarise(lifeExp= median(lifeExp)) %>%  
  ggplot(aes(x = year, y = lifeExp, color = continent))+
  geom_point(size = 1.5)+
  geom_smooth(method = "lm", aes(fill = continent))
## `summarise()` has grouped output by 'continent'. You can override using the
## `.groups` argument.
## `geom_smooth()` using formula = 'y ~ x'

Biểu Đồ phân tán

plt <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp))
plt

# thêm các điểm trong một lớp khác
plt + geom_point()

# tô màu theo chúng theo lục địa
plt + geom_point(aes(color = continent))

# thêm một đường cong được làm mịn cho tất cả dữ liệu
plt+geom_point(aes(color = continent))+
  geom_smooth(method = "loess")
## `geom_smooth()` using formula = 'y ~ x'

# quan sát các biến dễ hơn trên thang log
plt + geom_point(aes(color = continent))+
  geom_smooth(method = "loess")+
  scale_x_log10()
## `geom_smooth()` using formula = 'y ~ x'

# tự làm 
plt + geom_point(aes(color = continent))+
  geom_smooth(method = "loess")+
  scale_x_log10(labels = scales::comma)
## `geom_smooth()` using formula = 'y ~ x'

# di chuyển chú giải
plt + geom_point(aes(color = continent))+
  geom_smooth(method = "loess")+
  scale_x_log10(labels = scales::comma)+
  theme(legend.position = c(0.8,0.2))
## `geom_smooth()` using formula = 'y ~ x'

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
g <- crosstalk::SharedData$new(gapminder, ~continent)
gg <- ggplot(g, aes(x = gdpPercap, y = lifeExp, color = continent, frame = year))+
  geom_point(aes(size = pop, ids = country))+
  geom_smooth(se = F, method = "lm")+
  scale_x_log10()
## Warning in geom_point(aes(size = pop, ids = country)): Ignoring unknown
## aesthetics: ids
ggplotly(gg) %>%
  highlight("plotly_hover")
## `geom_smooth()` using formula = 'y ~ x'
## Setting the `off` event (i.e., 'plotly_doubleclick') to match the `on` event (i.e., 'plotly_hover'). You can change this default via the `highlight()` function.