#Bài tập 1:

library(matrixcalc)
#Định nghĩa ma trận A
A <- matrix(c(1, 1, 3, 5, 2, 6, -2, -1, -3), nrow = 3, ncol = 3, byrow = TRUE)
A
##      [,1] [,2] [,3]
## [1,]    1    1    3
## [2,]    5    2    6
## [3,]   -2   -1   -3

##Ý a:

#Tính A^3
A3 <- matrix.power(A, 3)
A3
##      [,1] [,2] [,3]
## [1,]    0    0    0
## [2,]    0    0    0
## [3,]    0    0    0
#Kiểm tra xem A^3 = 0 hay không 
zero <- all(A3 == 0)
zero
## [1] TRUE

##Ý b:

# Tính tổng của cột thứ 1 và cột thứ 2
col_sum <- colSums(A[, 1:2])

# Thay thế cột thứ 3 bằng tổng của cột thứ 1 và cột thứ 2
A[, 3] -> col_sum
print(A)
##      [,1] [,2] [,3]
## [1,]    1    1    3
## [2,]    5    2    6
## [3,]   -2   -1   -3

#Bài tập 2:

# Sử dụng hàm outer để tính toán tổng của các phần tử từ hai vector
vec1 <- 0:4
vec2 <- 0:4
matrix <- outer(vec1, vec2, "+")
# In ma trận
print(matrix)
##      [,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:

# Định nghĩa ma trận trọng số A
A <- matrix(c(1, 2, 3, 4, 5,
              2, 1, 2, 3, 4,
              3, 2, 1, 2, 3,
              4, 3, 2, 1, 2,
              5, 4, 3, 2, 1), nrow = 5, ncol = 5, byrow = TRUE)

# Định nghĩa ma trận y
y <- c(7, -1, -3, 5, 17)

# Giải hệ phương trình
x <- solve(A, y)
print(x)
## [1] -2  3  5  2 -4

#Bài tập 4:

i <- matrix(rep(1:20, each = 5), nrow = 20, ncol = 5)
j <- matrix(rep(1:5, times = 20), nrow = 20, ncol = 5)
S <- sum(i^4 / (3 + j))
S
## [1] 639215.3

#Bài tập 5:

library(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
library(ggplot2)
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
## 
##     combine

##Ý 1:

vietnamdata <- gapminder %>%
  filter(country == "Vietnam")

##Ý 2:

average_life_expectancy <- vietnamdata %>%
  group_by(year) %>%
  summarize(avg_life_expect = mean(lifeExp))
print(average_life_expectancy)
## # A tibble: 12 × 2
##     year avg_life_expect
##    <int>           <dbl>
##  1  1952            40.4
##  2  1957            42.9
##  3  1962            45.4
##  4  1967            47.8
##  5  1972            50.3
##  6  1977            55.8
##  7  1982            58.8
##  8  1987            62.8
##  9  1992            67.7
## 10  1997            70.7
## 11  2002            73.0
## 12  2007            74.2
Asia <- gapminder %>%
  filter(year == 2007 & continent == "Asia") %>%
  select(country, gdpPercap)

Europe <- gapminder %>%
  filter(year == 2007 & continent == "Europe") %>%
  select(country, gdpPercap)

 ggplot(Asia, aes(x = reorder(country, -gdpPercap), y = gdpPercap)) +
  geom_bar(stat = "identity", fill = "pink") +
  coord_flip() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(x = "Country", y = "GDP", title = "GDP Châu Á (2007)") -> plot_1

 ggplot(Europe, aes(x = reorder(country, -gdpPercap), y = gdpPercap)) +
  geom_bar(stat = "identity", fill = "violet") +
  coord_flip() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(x = "Country", y = "GDP", title = "GDP Châu Âu (2007)") -> plot_2
grid.arrange(plot_1, plot_2, ncol = 2)

Nhận xét: Dựa vào biểu đồ ta thấy Châu Á và Châu Âu có sự đa dạng về thu nhập GDP của các nước. Có một số nước ở châu Âu có thu nhập GDP cao hơn so với các nước châu Á. Điều này cho thấy mức độ phát triển kinh tế của một số nước châu Âu đứng đầu thế giới vào năm 2007.Tuy nhiên, châu Á cũng có nhiều nước có thu nhập GDP tăng nhanh và đạt mức đáng kể, như Trung Quốc và Ấn Độ. Điều này cho thấy sự phát triển kinh tế đáng kể của châu Á trong thập kỷ trước.

#Bài tập 6:

library(ggplot2)
library(dplyr)    # data munging
library(scales) 
library(gapminder)
if(!require(gapminder)) {install.packages("gapminder"); library(gapminder)}
gap1 <- ggplot(data=gapminder, aes(x=continent, y=lifeExp, fill=continent))
gap1 +
    geom_boxplot(outlier.size=2)

##Xoá chú thích

gap1 <- ggplot(data=gapminder, aes(x=continent, y=lifeExp, fill=continent)) +  guides(fill=FALSE)
## 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.
gap1 +
    geom_boxplot(outlier.size=2)

##Vẽ đồ thị theo chiều ngang

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

##Thử geom_violin()

gap1 <- ggplot(data=gapminder, aes(x=continent, y=lifeExp, fill=continent)) +  guides(fill=FALSE)
gap1 +
    geom_violin(outlier.size=2)
## Warning in geom_violin(outlier.size = 2): Ignoring unknown parameters:
## `outlier.size`

##Vẽ biểu đồ phân bổ riêng biệt

# Load the gapminder dataset
data(gapminder)

# Create a boxplot facetted by continent
plot <- ggplot(gapminder, aes(x = continent, y = lifeExp)) +
  geom_boxplot() +
  labs(x = "Continent", y = "Life Expectancy") +
  theme_minimal() +
  facet_wrap(~continent, scales = "free")

# Display the plot
print(plot)

##vẽ biểu đồ GDP theo thang log. Thêm một lớp khác biến đổi trục x thành log10(gdpPercap)

plot <- ggplot(gapminder, aes(x = log10(gdpPercap), y = gdpPercap)) +
  geom_point() +
  scale_x_continuous(name = "log10(gdpPercap)", trans = "log10") +
  scale_y_continuous(name = "GDP per capita") +
  labs(title = "GDP per capita (log scale)") +
  theme_minimal()
print(plot)

##Vẽ GDP theo thang Log

plot <- ggplot(gapminder, aes(x = log(gdpPercap), y = gdpPercap)) +
  geom_line() +
  scale_x_continuous(name = "log(gdpPercap)") +
  scale_y_continuous(trans = "log10", name = "GDP per capita (log scale)") +
  labs(title = "GDP per capita (log scale)", x = "log(gdpPercap)", y = "GDP per capita (log scale)") +
  theme_minimal()
print(plot)

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

##Sử dụng sơ đồ trên để tìm giá trị trung bình và độ lệch chuẩn cho tất cả các quốc gia.

# Tính giá trị trung bình tuổi thọ trung bình cho tất cả các quốc gia
mean_lifeExp <- gapminder %>%
  group_by(country) %>%
  summarize(mean_lifeExp = mean(lifeExp))
mean_lifeExp
## # A tibble: 142 × 2
##    country     mean_lifeExp
##    <fct>              <dbl>
##  1 Afghanistan         37.5
##  2 Albania             68.4
##  3 Algeria             59.0
##  4 Angola              37.9
##  5 Argentina           69.1
##  6 Australia           74.7
##  7 Austria             73.1
##  8 Bahrain             65.6
##  9 Bangladesh          49.8
## 10 Belgium             73.6
## # ℹ 132 more rows
# Tính độ lệch chuẩn tuổi thọ trung bình cho tất cả các quốc gia
sd_lifeExp <- gapminder %>%
  group_by(country) %>%
  summarize(sd_lifeExp = sd(lifeExp))
sd_lifeExp
## # A tibble: 142 × 2
##    country     sd_lifeExp
##    <fct>            <dbl>
##  1 Afghanistan       5.10
##  2 Albania           6.32
##  3 Algeria          10.3 
##  4 Angola            4.01
##  5 Argentina         4.19
##  6 Australia         4.15
##  7 Austria           4.38
##  8 Bahrain           8.57
##  9 Bangladesh        9.03
## 10 Belgium           3.78
## # ℹ 132 more rows

##Lập một biểu đồ về sự phân bố của giá trị trung bình và độ lệch chuẩn.

summary_data <- gapminder %>%
  group_by(country) %>%
  summarize(mean_lifeExp = mean(lifeExp),
            sd_lifeExp = sd(lifeExp))
# Biểu đồ phân bố của giá trị trung bình và độ lệch chuẩn
ggplot() +
  geom_density(data = summary_data, aes(x = mean_lifeExp), fill = "pink", alpha = 0.5) +
  geom_density(data = summary_data, aes(x = sd_lifeExp), fill = "violet", alpha = 0.5) +
  labs(title = "Phân phối của Giá trị Trung bình và Độ lệch chuẩn",
       x = "Tuổi thọ trung bình",
       y = "Mật độ") +
  scale_fill_manual(values = c("pink", "violet"),
                    labels = c("Trung bình", "Độ lệch chuẩn"),
                    name = "Thống kê") +
  theme_minimal()