R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:


## Including Plots

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Install dan panggil library

Pastikan sudah terinstall

install.packages("rvest")
install.packages("dplyr")
install.packages("stringr")
install.packages("ggplot2")
install.packages("markdown")
install.packages("knitr")
library(rvest)
library(dplyr)
library(stringr)
library(markdown)
library(knitr)

URL halaman Wikipedia

url <- “https://id.wikipedia.org/wiki/Daftar_kota_di_Indonesia_menurut_jumlah_penduduk

Baca halaman

web <- read_html(url)

Ambil tabel pertama yang sesuai

tabel <- web %\>% html_elements("table.wikitable") %\>% .[[1]] %\>% html_table(fill = TRUE)

Bersihkan dan ubah nama kolom

colnames(tabel) <- c("No", "Kota", "Provinsi", "Penduduk_2024", "Penduduk_2014", "Perubahan")

Bersihkan data dari karakter non-angka jika perlu

tabel <- tabel %\>% mutate( Penduduk_2024 = as.numeric(str_replace_all(Penduduk_2024, "\\D", "")), Penduduk_2014 = as.numeric(str_replace_all(Penduduk_2014, "\\D", "")), Perubahan = as.numeric(str_replace_all(Perubahan, "[\^\\\\d-]", "")) )

Tampilkan data

head(tabel)
#No Kota                            Provinsi                      Penduduk_2024 Penduduk_2014 Perubahan
  <dbl> <chr>                           <chr>                         <chr>         <chr>             <dbl>
#     1 Kota Administrasi Jakarta Timur Daerah Khusus Ibukota Jakarta 3.230.417     2.852.887          378.
#     2 Kota Surabaya                   Jawa  Timur                   3.018.022     2.805.906          212.
#     3 Kota Bandung                    Jawa Barat                    2.591.763     2.465.466          126.
#     4 Kota Bekasi                     Jawa  Barat                   2.572.209     2.339.463          233.
#     5 Kota Administrasi Jakarta Barat Daerah Khusus Ibukota Jakarta 2.556.752     2.234.397          322.
#     6 Kota Medan                      Sumatera Utara                2.546.452     2.381.053          165.

Ambil 10 kota terpadat berdasarkan penduduk 2024

top10 <- tabel %>%
  arrange(desc(Penduduk_2024)) %>%
  slice(1:10)

Buat grafik batang

ggplot(top10, aes(x = reorder(Kota, Penduduk_2024), y = Penduduk_2024)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  coord_flip() +
  labs(
    title = "10 Kota Terpadat di Indonesia (2024)",
    x = "Kota",
    y = "Jumlah Penduduk"
  ) +
 theme_minimal()