library(rvest)
## Warning: package 'rvest' was built under R version 4.2.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.3
##
## 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
link <- "https://en.wikipedia.org/wiki/List_of_Formula_One_drivers"
page <- read_html(link)
drivers_F1 <- html_element(page, "table.sortable") %>%
html_table()
head(drivers_F1) # hiện 6 dòng thông tin đầu về các tay đua tiên trong danh sách
## # A tibble: 6 × 11
## `Driver name` Nationality `Seasons competed` `Drivers' Championships`
## <chr> <chr> <chr> <chr>
## 1 Carlo Abate Italy 1962–1963 0
## 2 George Abecassis United Kingdom 1951–1952 0
## 3 Kenny Acheson United Kingdom 1983, 1985 0
## 4 Andrea de Adamich Italy 1968, 1970–1973 0
## 5 Philippe Adams Belgium 1994 0
## 6 Walt Ader United States 1950 0
## # ℹ 7 more variables: `Race entries` <chr>, `Race starts` <chr>,
## # `Pole positions` <chr>, `Race wins` <chr>, Podiums <chr>,
## # `Fastest laps` <chr>, `Points[a]` <chr>
drivers_F1$`Drivers' Championships` <- substr(drivers_F1$`Drivers' Championships`,
start = 1, stop = 1) # trích xuất kí tự đầu tiên ở mục số lần vô địch vì trong mục này sẽ có năm nên chỉ lấy kí tự đầu tiên nghĩa là lấy số lần vô địch
write.csv(drivers_F1, "F1_drivers.csv", row.names = FALSE)
drivers_F1 %>%
group_by(Nationality) %>%
summarise(championship_country = sum(as.double(`Drivers' Championships`))) %>%
arrange(desc(championship_country))
## Warning: There was 1 warning in `summarise()`.
## ℹ In argument: `championship_country = sum(as.double(`Drivers'
## Championships`))`.
## ℹ In group 31: `Nationality = "Nationality"`.
## Caused by warning:
## ! NAs introduced by coercion
## # A tibble: 49 × 2
## Nationality championship_country
## <chr> <dbl>
## 1 United Kingdom 20
## 2 Germany 12
## 3 Brazil 8
## 4 Argentina 5
## 5 Australia 4
## 6 Austria 4
## 7 Finland 4
## 8 France 4
## 9 Italy 3
## 10 Netherlands 2
## # ℹ 39 more rows
drivers_F1 %>%
group_by(`Driver name`) %>%
summarise(championship_pilot = sum(as.double(`Drivers' Championships`))) %>%
arrange(desc(championship_pilot))
## Warning: There was 1 warning in `summarise()`.
## ℹ In argument: `championship_pilot = sum(as.double(`Drivers' Championships`))`.
## ℹ In group 212: `Driver name = "Driver name"`.
## Caused by warning:
## ! NAs introduced by coercion
## # A tibble: 869 × 2
## `Driver name` championship_pilot
## <chr> <dbl>
## 1 Lewis Hamilton~ 7
## 2 Michael Schumacher^ 7
## 3 Juan Manuel Fangio^ 5
## 4 Alain Prost^ 4
## 5 Sebastian Vettel^ 4
## 6 Ayrton Senna^ 3
## 7 Jack Brabham^ 3
## 8 Jackie Stewart^ 3
## 9 Nelson Piquet^ 3
## 10 Niki Lauda^ 3
## # ℹ 859 more rows
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
drivers_F1 %>%
filter(`Pole positions` > 1) %>%
ggplot(aes(x = as.double(`Pole positions`), y = as.double(`Drivers' Championships`))) +
geom_point(position = "jitter") +
labs(y = "Championships won", x = "Pole positions") +
theme_minimal()
## Warning in FUN(X[[i]], ...): NAs introduced by coercion
## Warning in FUN(X[[i]], ...): NAs introduced by coercion
## Warning in FUN(X[[i]], ...): NAs introduced by coercion
## Warning in FUN(X[[i]], ...): NAs introduced by coercion
## Warning: Removed 1 rows containing missing values (`geom_point()`).
library(WDI)
## Warning: package 'WDI' was built under R version 4.2.3
h <- WDIsearch("health")
data.table::data.table(h)
## indicator
## 1: 110600
## 2: 5.13.01.01.hlthsurv
## 3: 5.51.01.06.matern
## 4: 9080000
## 5: BI.EMP.FRML.HE.PB.ZS
## ---
## 300: UIS.ONTRACK.THREE.DOMAINS
## 301: UIS.ONTRACK.THREE.DOMAINS.F
## 302: UIS.ONTRACK.THREE.DOMAINS.GPIA
## 303: UIS.ONTRACK.THREE.DOMAINS.M
## 304: VC.IHR.IPBH.P5
## name
## 1: 110600:HEALTH - HHC (Category)
## 2: Health survey
## 3: Maternal health
## 4: 9080000:ACTUAL HEALTH
## 5: Health workers, as a share of public formal employees
## ---
## 300: Proportion of children aged 24-59 months who are developmentally on track in health, learning and psychosocial well-being, both sexes (%)
## 301: Proportion of children aged 24-59 months who are developmentally on track in health, learning and psychosocial well-being, female (%)
## 302: Proportion of children aged 24-59 months who are developmentally on track in health, learning and psychosocial well-being, adjusted gender parity index (GPIA)
## 303: Proportion of children aged 24-59 months who are developmentally on track in health, learning and psychosocial well-being, male (%)
## 304: Intentional homicides, international public health sources (per 100,000 people)
hl <- WDI(indicator = "BI.EMP.FRML.HE.PB.ZS")
htl <- na.omit(hl)
data.table::data.table(htl)
## country iso2c iso3c year BI.EMP.FRML.HE.PB.ZS
## 1: Albania AL ALB 2005 0.16654412
## 2: Albania AL ALB 2002 0.15182033
## 3: Argentina AR ARG 2017 0.11470459
## 4: Argentina AR ARG 2014 0.12238789
## 5: Argentina AR ARG 2013 0.11608516
## ---
## 267: Zambia ZM ZMB 2010 0.15530933
## 268: Zambia ZM ZMB 2008 0.14228462
## 269: Zambia ZM ZMB 2004 0.15562588
## 270: Zambia ZM ZMB 2002 0.12312683
## 271: Zimbabwe ZW ZWE 2011 0.08749893
hvn <- WDI(indicator = "BI.EMP.FRML.HE.PB.ZS",country = "VN")
hvn <- na.omit(hvn)
data.table::data.table(hvn)
## country iso2c iso3c year BI.EMP.FRML.HE.PB.ZS
## 1: Vietnam VN VNM 2009 0.07857248
## 2: Vietnam VN VNM 2007 0.06633190
health2 <- WDI(indicator = "BI.EMP.PUBS.FE.HE.ZS")
health2<- na.omit(health2)
head(health2)
## country iso2c iso3c year BI.EMP.PUBS.FE.HE.ZS
## 37 Albania AL ALB 2005 0.9306692
## 40 Albania AL ALB 2002 0.9132696
## 76 Angola AO AGO 2008 0.6703777
## 130 Argentina AR ARG 2017 0.4439777
## 133 Argentina AR ARG 2014 0.4168458
## 134 Argentina AR ARG 2013 0.4162496
health3 <- WDI(indicator = "BI.EMP.PWRK.HE.PB.ZS")
health3 <- na.omit(health3)
head(health3)
## country iso2c iso3c year BI.EMP.PWRK.HE.PB.ZS
## 37 Albania AL ALB 2005 0.159959465
## 40 Albania AL ALB 2002 0.145354003
## 66 Angola AO AGO 2018 0.001045144
## 70 Angola AO AGO 2014 0.013787351
## 76 Angola AO AGO 2008 0.093683116
## 84 Angola AO AGO 2000 0.107649237
health4 <- WDI(indicator = "BI.EMP.TOTL.HE.PB.ZS")
health4 <- na.omit(health4)
head(health4)
## country iso2c iso3c year BI.EMP.TOTL.HE.PB.ZS
## 37 Albania AL ALB 2005 0.159959465
## 40 Albania AL ALB 2002 0.145354003
## 66 Angola AO AGO 2018 0.001045144
## 70 Angola AO AGO 2014 0.013787351
## 76 Angola AO AGO 2008 0.093683116
## 84 Angola AO AGO 2000 0.107649237
health5 <- WDI(indicator = "BI.PWK.PRVS.HS.ZS")
health5 <- na.omit(health5)
head(health5)
## country iso2c iso3c year BI.PWK.PRVS.HS.ZS
## 8 Afghanistan AF AFG 2013 0
## 10 Afghanistan AF AFG 2011 0
## 14 Afghanistan AF AFG 2007 0
## 18 Afghanistan AF AFG 2003 0
## 30 Albania AL ALB 2012 0
## 34 Albania AL ALB 2008 0
health6 <- WDI(indicator = "BI.PWK.PUBS.HE.FE.ZS")
health6 <- na.omit(health6)
head(health6)
## country iso2c iso3c year BI.PWK.PUBS.HE.FE.ZS
## 37 Albania AL ALB 2005 0.7995719
## 40 Albania AL ALB 2002 0.8365431
## 70 Angola AO AGO 2014 0.4822064
## 76 Angola AO AGO 2008 0.6298007
## 84 Angola AO AGO 2000 0.6341168
## 130 Argentina AR ARG 2017 0.6578633
health7 <- WDI(indicator = "BI.WAG.PREM.HE")
health7 <- na.omit(health7)
head(health7)
## country iso2c iso3c year BI.WAG.PREM.HE
## 37 Albania AL ALB 2005 -0.20310804
## 40 Albania AL ALB 2002 0.07844495
## 130 Argentina AR ARG 2017 -0.04820478
## 133 Argentina AR ARG 2014 -0.02954306
## 134 Argentina AR ARG 2013 -0.01467949
## 135 Argentina AR ARG 2012 -0.02485598
health8 <- WDI(indicator = "CC.TCFD.COMP.HC")
health8 <- na.omit(health8)
head(health8)
## country iso2c iso3c year CC.TCFD.COMP.HC
## 836 Australia AUS 2021 1
## 3803 Denmark DNK 2021 3
## 4838 France FRA 2021 1
## 5183 Germany DEU 2021 1
## 6287 India IND 2021 2
## 6701 Israel ISR 2021 1
health9 <- WDI(indicator = "DT.ODA.DACD.HLTH.BAS.CD")
health9 <- na.omit(health9)
head(health9)
## country iso2c iso3c year DT.ODA.DACD.HLTH.BAS.CD
## 2 Africa AFR 2011 3458380340
## 3 Africa AFR 2010 3010795885
## 4 Africa AFR 2009 2995521141
## 5 Africa AFR 2008 2550522246
## 6 Africa AFR 2007 1945987680
## 7 Africa AFR 2006 1445580561
health10 <- WDI(indicator = "FC.XPD.HE.CR")
health10 <- na.omit(health10)
head(health10)
## country iso2c iso3c year FC.XPD.HE.CR
## 1 Nanggroe Aceh Darussalam, Prop. 2020 2.019099e+12
## 2 Nanggroe Aceh Darussalam, Prop. 2019 2.369495e+12
## 3 Nanggroe Aceh Darussalam, Prop. 2018 1.957056e+12
## 4 Nanggroe Aceh Darussalam, Prop. 2017 1.718797e+12
## 5 Nanggroe Aceh Darussalam, Prop. 2016 1.377824e+12
## 6 Nanggroe Aceh Darussalam, Prop. 2015 1.510824e+11
Tạo một fucntion xếp hạng lượt xem của các bộ phim theo thứ tự giảm dần
# Tạo một dataframe chứa thông tin về các bộ phim
movies <- data.frame(title = c("Phim A", "Phim B", "Phim C", "Phim D"),
view_count = c(500, 1000, 250, 750))
# Sử dụng hàm để xếp hạng các bộ phim
ranked_movies <- rank(movies)
# In kết quả
print(ranked_movies)
## title view_count <NA> <NA> <NA> <NA> <NA>
## 5 6 7 8 2 4 1
## <NA>
## 3
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.3
## Warning: package 'tibble' was built under R version 4.2.3
## Warning: package 'tidyr' was built under R version 4.2.3
## Warning: package 'readr' was built under R version 4.2.3
## Warning: package 'purrr' was built under R version 4.2.3
## Warning: package 'stringr' was built under R version 4.2.3
## Warning: package 'forcats' was built under R version 4.2.3
## Warning: package 'lubridate' was built under R version 4.2.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ lubridate 1.9.2 ✔ tibble 3.2.1
## ✔ purrr 1.0.1 ✔ tidyr 1.3.0
## ✔ readr 2.1.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ readr::guess_encoding() masks rvest::guess_encoding()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
airquality |> ggplot(map=aes(x=Solar.R, y=Temp)) +
geom_point(na.rm = T, color = "red") +
xlab('Bức xạ Mặt Trời') +
ylab('Nhiệt độ')
- Biểu đồ thể hiện lượng bức xạ Mặt Trời theo nhiệt độ và mối quan hệ
giữa chúng
airquality |> ggplot(aes(x=Solar.R, y=Temp)) +
geom_smooth(formula = y ~ x, method = 'lm',na.rm =T, color ='green')+
geom_point(na.rm = T,color = "red") +
labs(title = 'Đồ thị dạng scatter',x='Bức xạ Mặt Trời',y='Nhiệt độ')
- Biểu đồ thể hiện tổng lượng bức xạ mặt trời theo nhiệt độ (point &
line)
airquality |> ggplot(aes(x=Solar.R, y=Temp))+
geom_point(na.rm=T,color='red') +
geom_line(na.rm=T,color='purple')+
xlab('Bức xạ Mặt Trời') +
ylab('Nhiệt độ')
- Biểu đồ thể hiện tương quan giữa bức xạ Mặt Trời và tốc độ gió theo
tháng
airquality |> ggplot(aes(x=Solar.R,y=Wind, color = Month)) +
geom_point(na.rm = T)+
xlab('Bức xạ Mặt Trời')+
ylab('Tốc độ gió')
airquality |> ggplot(aes(x=Solar.R,y=Wind))+
geom_point(na.rm=T, color='orange')+
geom_point(data=airquality|> filter(Month == '5'),na.rm =T, color='blue')+
xlab('Bức xạ Mặt Trời')+
ylab('Tốc độ gió')
- Vẽ thành nhiều đồ thị thể hiện mối quan hệ giữa tổng bức xạ mặt trời
và tốc độ gió theo từng tháng
airquality |> ggplot(aes(x=Solar.R,y=Wind))+
geom_point(aes(color=Month), na.rm = T)+
geom_smooth(formula = y ~ x, method = 'lm', na.rm = T)+
facet_grid(.~Month)+
xlab('Bức xạ Mặt Trời')+
ylab('Tốc độ gió')
airquality |> ggplot(aes(x=Solar.R,y=Wind))+
geom_point(aes(color=Month), na.rm = T)+
geom_smooth(formula = y ~ x, method = 'lm', na.rm = T)+
facet_grid(Month~.)+
xlab('Bức xạ Mặt Trời')+
ylab('Tốc độ gió')
data("diamonds")
diamonds|> ggplot(aes(x=cut))+
geom_bar(fill='orange',color='red')
diamonds|>ggplot(aes(x=cut))+
geom_bar(aes(fill=cut),width = 0.5)
- Biểu đồ thể hiện chất lượng của kim cương và độ trong trẻo
diamonds|> ggplot(aes(x=cut))+
geom_bar(aes(fill=clarity))
diamonds|> ggplot(aes(x=cut))+
geom_bar(aes(fill = clarity),position = "dodge")
diamonds|>ggplot(aes(x=cut))+
geom_bar(aes(fill=clarity),position = "dodge")+
coord_flip()
library(tidyverse)
airquality_long <- pivot_longer(airquality, cols = -c(Month, Day), names_to = "Variable", values_to = "Value")
ozone_avgD <- airquality_long %>%
filter(Variable == "Ozone") %>%
group_by(Day) %>%
summarize(Average_Ozone = mean(Value, na.rm = TRUE))
print(ozone_avgD)
## # A tibble: 31 × 2
## Day Average_Ozone
## <int> <dbl>
## 1 1 77.8
## 2 2 43
## 3 3 33.2
## 4 4 62.3
## 5 5 48.7
## 6 6 41.5
## 7 7 54.2
## 8 8 57
## 9 9 61.4
## 10 10 49.3
## # ℹ 21 more rows
giống như với long ta tạo ra bảng dạng wide cũng tương tự nhưng dùng lệnh pivot_wider
library(tidyr)
wider_ozoneMontth <- airquality %>%
group_by(Month) %>%
summarise(mean_Ozone = mean(Ozone, na.rm = TRUE)) %>%
pivot_wider(names_from = "Month", values_from = "mean_Ozone")
print(wider_ozoneMontth)
## # A tibble: 1 × 5
## `5` `6` `7` `8` `9`
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 23.6 29.4 59.1 60.0 31.4
mean(airquality$T)
## [1] 77.88235
var(airquality$T)
## [1] 89.59133
sd(airquality$T)
## [1] 9.46527
q1 <- quantile(airquality$T, prob=0.25)
trungvi <- quantile(airquality$T, prob = 0.5)
q3 <- quantile(airquality$T, prob = 0.75)
print(q1)
## 25%
## 72
print(trungvi)
## 50%
## 79
print(q3)
## 75%
## 85
summary(airquality)
## Ozone Solar.R Wind Temp
## Min. : 1.00 Min. : 7.0 Min. : 1.700 Min. :56.00
## 1st Qu.: 18.00 1st Qu.:115.8 1st Qu.: 7.400 1st Qu.:72.00
## Median : 31.50 Median :205.0 Median : 9.700 Median :79.00
## Mean : 42.13 Mean :185.9 Mean : 9.958 Mean :77.88
## 3rd Qu.: 63.25 3rd Qu.:258.8 3rd Qu.:11.500 3rd Qu.:85.00
## Max. :168.00 Max. :334.0 Max. :20.700 Max. :97.00
## NA's :37 NA's :7
## Month Day
## Min. :5.000 Min. : 1.0
## 1st Qu.:6.000 1st Qu.: 8.0
## Median :7.000 Median :16.0
## Mean :6.993 Mean :15.8
## 3rd Qu.:8.000 3rd Qu.:23.0
## Max. :9.000 Max. :31.0
##
Mô tả: Đo chất lượng không khí hàng ngày ở New York, tháng 5 đến tháng 9 năm 1973. Một khung dữ liệu với 153 quan sát trên 6 biến. Ý nghĩa các biến có trong dữ liệu
Ozone: Nồng độ Ozone tích lũy (ppb)
Solar.R: Tổng lượng bức xạ mặt trời trong đơn vị langley (lang)
Wind: Tốc độ Gió (mph)
Temp: Nhiệt độ (độ F)
Month: số Tháng (5-9)
Day: số Ngày trong tháng (1-31)
Dữ liệu được lấy từ Cục Bảo an Bang New York (dữ liệu ozone) và Dịch vụ Thời tiết Quốc gia (dữ liệu khí tượng).
data("airquality")
d <- airquality
str(d)
## 'data.frame': 153 obs. of 6 variables:
## $ Ozone : int 41 36 12 18 NA 28 23 19 8 NA ...
## $ Solar.R: int 190 118 149 313 NA NA 299 99 19 194 ...
## $ Wind : num 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
## $ Temp : int 67 72 74 62 56 66 65 59 61 69 ...
## $ Month : int 5 5 5 5 5 5 5 5 5 5 ...
## $ Day : int 1 2 3 4 5 6 7 8 9 10 ...
head(d)
## Ozone Solar.R Wind Temp Month Day
## 1 41 190 7.4 67 5 1
## 2 36 118 8.0 72 5 2
## 3 12 149 12.6 74 5 3
## 4 18 313 11.5 62 5 4
## 5 NA NA 14.3 56 5 5
## 6 28 NA 14.9 66 5 6
tail(d)
## Ozone Solar.R Wind Temp Month Day
## 148 14 20 16.6 63 9 25
## 149 30 193 6.9 70 9 26
## 150 NA 145 13.2 77 9 27
## 151 14 191 14.3 75 9 28
## 152 18 131 8.0 76 9 29
## 153 20 223 11.5 68 9 30
names(d) <- c('O','S','W','T','M','D')
Temp <- d$T
#nhiệt độ lớn hơn 80 độ F
Temp <- Temp[Temp>80]
#Nhiệt độ lớn hơn 70 và nhỏ hơn 90 (độ F)
Temp7090 <- Temp[Temp>70&Temp<90]
Phân tổ Temp thành 4 tổ
table(cut(Temp,4))
##
## (81,85] (85,89] (89,93] (93,97]
## 34 17 13 4
lấy dữ liệu từ vị trí dòng 2 cột 5
d[2,5]
## [1] 5
biểu đồ cho số gió (W)
barplot(table(d$W),xlab="Wind",ylab="Frequency")