U.UNIQUE / PRACTICUM NOTESSTATISTICS & DATA SCIENCE
IPB UNIVERSITYPRACTICUM 02
Daftar IsiTable of Contents

Introduction to SQL

Query, pengolahan database, dan implementasi RStudioQuerying, database manipulation, and RStudio implementation

Sebelum membangun model statistika atau machine learning, kita perlu memastikan bahwa data yang digunakan sesuai dengan pertanyaan analisis. Dalam praktik, informasi tidak selalu tersimpan dalam satu file CSV. Sebuah toko musik digital, misalnya, menyimpan informasi pelanggan, album, track, dan transaksi pada tabel yang berbeda. Memindahkan seluruh tabel ke R setiap kali membutuhkan satu ringkasan tidak selalu diperlukan.Before fitting statistical or machine learning models, we need to ensure that the data match the analytical question. In practice, information is not always stored in a single CSV file. A digital music store, for example, keeps customer, album, track and transaction information in separate tables. Transferring every table into R whenever a summary is needed is not always necessary.

Bagaimana cara mengetahui album mana yang mempunyai track terbanyak, pelanggan berasal dari negara mana, atau berapa rata-rata nilai transaksi pada setiap negara? Ketiga pertanyaan tersebut membutuhkan cara memilih, menyaring, mengelompokkan, dan terkadang menggabungkan data. Structured Query Language (SQL) menyediakan perintah untuk melakukan pekerjaan tersebut langsung pada database.How can we find the album with the most tracks, the countries customers come from, or the average transaction value in each country? These questions require selecting, filtering, grouping and sometimes combining data. Structured Query Language (SQL) provides commands to perform these operations directly in a database.

Pada praktikum ini, kita menggunakan database Chinook. Mula-mula kita mencoba query melalui DB Browser for SQLite agar hubungan antara perintah dan hasilnya terlihat jelas. Kemudian database yang sama dihubungkan ke RStudio menggunakan DBI dan RSQLite. Dengan dplyr dan dbplyr, kita dapat menyusun operasi menggunakan sintaks R, sementara SQLite menjalankan query. Hasil akhirnya dapat digunakan untuk visualisasi dan analisis lanjutan dengan ggplot2.In this practicum, we use the Chinook database. We first run queries in DB Browser for SQLite to see how commands change results. Then we connect the same database to RStudio using DBI and RSQLite. With dplyr and dbplyr, we can express operations in R syntax while SQLite executes the query. The resulting data can be visualized and analyzed using ggplot2.

SQLiteDatabase ChinookChinook database
→
SQLQuery dataQuery data
→
RStudioDBI · dbplyr
→
HasilResultsggplot2

Persiapan praktikumGetting started

Untuk mempraktikkan SQL, kita memerlukan mesin database dan antarmuka untuk mengirimkan perintah. SQLite menyimpan database dalam sebuah file, sehingga kita tidak perlu menyiapkan server database terpisah. DB Browser for SQLite menyediakan antarmuka grafis untuk melihat struktur tabel dan mencoba query sebelum menghubungkannya ke R.To practice SQL, we need a database engine and an interface for submitting commands. SQLite stores a database in a file, so a separate database server is not required. DB Browser for SQLite provides a graphical interface to inspect table structures and try queries before connecting to R.

Simpan database di folder project RStudio yang akan digunakan selama praktikum. Dengan demikian, file yang dibuka di DB Browser dan file yang diakses dari R merujuk pada data yang sama. Gunakan salinan tersendiri jika ingin mencoba perintah yang mengubah isi database.Keep the database in the RStudio project folder used during the practicum. The file opened in DB Browser and the file accessed from R will then refer to the same data. Use a separate copy when trying commands that modify the database.

Instal DB Browser for SQLite, ikuti video instalasi bila diperlukan, lalu buka aplikasinya. Unduh file Chinook_Sqlite.sqlite dan simpan di folder praktikum yang juga digunakan RStudio.Install DB Browser for SQLite, follow the installation video if needed, and launch it. Download Chinook_Sqlite.sqlite and save it in the practicum folder also used by RStudio.

Membuka database di DB BrowserOpening the database in DB Browser

Langkah 1. Klik Open Database.Step 1. Click Open Database.

Step 1: opening the database
Langkah 1 membuka databaseStep 1: opening the database

Langkah 2. Pilih Chinook_Sqlite.sqlite pada direktori, lalu klik Open.Step 2. Select Chinook_Sqlite.sqlite in your directory and click Open.

Step 2: opening the database
Langkah 2 membuka databaseStep 2: opening the database

Langkah 3. Pastikan struktur tabel database muncul pada antarmuka.Step 3. Confirm the database structure appears in the interface.

Step 3: opening the database
Langkah 3 membuka databaseStep 3: opening the database

Gunakan tab Execute SQL untuk menuliskan query. Saat membuat tabel baru, gunakan salinan database agar file asli tetap aman.Use the Execute SQL tab to enter queries. When creating new tables, work on a copy to preserve the original database.

Mengenal database ChinookUnderstanding Chinook

Sebelum menulis query, identifikasi terlebih dahulu informasi yang tersedia dan unit observasi setiap tabel. Pada tabel Track, satu baris adalah satu track; pada Customer, satu baris adalah satu pelanggan; dan pada Invoice, satu baris adalah satu transaksi. Kesamaan nama variabel tidak berarti dua tabel memiliki unit observasi yang sama.Before writing a query, identify the available information and the observational unit of each table. A row in Track represents a track, a row in Customer a customer, and a row in Invoice a transaction. Matching column names do not mean that tables have the same observational unit.

Struktur relasional memungkinkan informasi artis disimpan sekali pada Artist, kemudian dihubungkan dengan Album menggunakan ArtistId. Cara ini menghindari pengulangan informasi yang sama pada setiap track. Saat membutuhkan informasi dari beberapa tabel, kita menggunakan key untuk menemukan pasangan baris yang tepat, bukan mengandalkan urutan penyimpanan.A relational structure allows artist information to be stored once in Artist and linked to Album through ArtistId. This avoids repeating the same information for each track. When information from multiple tables is required, keys identify matching records rather than relying on storage order.

Chinook adalah database contoh toko media digital. Database ini merupakan alternatif Northwind, tersedia untuk SQLite, MySQL, SQL Server, SQL Server Compact, PostgreSQL, Oracle, dan DB2, dan dapat dibuat melalui skrip SQL. Data media bersumber dari pustaka iTunes; data pelanggan dan pegawai bersifat fiktif; transaksi penjualan dibuat secara acak untuk periode empat tahun. Nama Chinook merujuk pada angin di Amerika Utara bagian barat, terutama Alberta selatan, Kanada.Chinook is a sample digital media store database. It is an alternative to Northwind, available for SQLite, MySQL, SQL Server, SQL Server Compact, PostgreSQL, Oracle and DB2, and can be created using a SQL script. Media data come from an iTunes library; customer and employee information is fictitious; sales were randomly generated over four years. Chinook refers to a wind in inland western North America, particularly southern Alberta, Canada.

Satu tabel memiliki kolom (field) dan baris (record). Primary key (PK) mengidentifikasi baris; foreign key (FK) merujuk pada key tabel lain. Contoh: Album.ArtistId merujuk Artist.ArtistId; satu artis dapat mempunyai banyak album.A table contains columns (fields) and rows (records). A primary key (PK) identifies rows; a foreign key (FK) references a key in another table. For example, Album.ArtistId references Artist.ArtistId; one artist can have many albums.

Original Chinook relationship diagram
Diagram relasi ChinookChinook relationship diagram

Pilih nama tabel untuk melihat field dan key. Coba mulai dari Artist, pindah ke Album, lalu Track; perhatikan bagaimana ArtistId dan AlbumId menghubungkan ketiganya.Select a table to inspect its fields and keys. Start from Artist, move to Album, then Track; observe how ArtistId and AlbumId connect them.

INTERACTIVE 01 · DATABASE EXPLORER

Jelajahi tabel dan keyExplore tables and keys

Gunakan nama tabel SQLite yang ditampilkan pada database. Diagram relasi dapat memakai konvensi penamaan berbeda.Use the SQLite table names shown in the database. The relationship diagram may use a different naming convention.

Query dasar SQLBasic SQL queries

Ketika membuka sebuah tabel, kita mungkin hanya membutuhkan sebagian kolomnya. SQL memungkinkan kita menentukan hasil secara eksplisit, tanpa menghapus atau mengubah data yang tersimpan. Bayangkan kita ingin melihat nama track, komposer, dan harga satuan; kolom durasi atau ukuran file tidak perlu ikut diambil.When opening a table, we may need only a few of its columns. SQL allows us to specify the desired result without deleting or modifying stored data. Suppose we want track names, composers and unit prices; duration and file size do not need to be retrieved.

Pada setiap contoh, coba jalankan query di tab Execute SQL pada DB Browser, lalu bandingkan hasilnya dengan tab R setelah koneksi disiapkan. Perhatikan apakah yang berubah adalah jumlah kolom, jumlah baris, atau hanya urutannya. Ketiga perubahan tersebut memiliki tujuan yang berbeda dalam analisis.For each example, run the query in the Execute SQL tab of DB Browser, then compare it with the R tab after setting up the connection. Observe whether the number of columns, the number of rows, or only their order changes. These transformations serve different analytical purposes.

SQL
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC
LIMIT 10;

Contoh 01 · SELECT — Memilih kolomExample 01 · SELECT — Select columns

Tabel Track menyimpan berbagai atribut media. Untuk membangun daftar katalog sederhana, pilih TrackId sebagai pengenal, Name sebagai judul, Composer sebagai informasi pencipta, dan UnitPrice sebagai harga. Dengan mengambil kolom yang diperlukan saja, hasil lebih ringkas dan mudah digunakan pada tahap berikutnya.Track stores various media attributes. To build a simple catalog, select TrackId as the identifier, Name as the title, Composer as creator information and UnitPrice as the price. Retrieving only the required columns keeps the result compact for later use.

Kolom yang disebutkan setelah SELECT saja yang ditampilkan. SELECT * memilih semua kolom.Only the columns named after SELECT are returned. SELECT * selects all columns.

SQL
SELECT TrackId, Name, Composer, UnitPrice
FROM Track;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
  TrackId                                    Name
1       1 For Those About To Rock (We Salute You)
2       2                       Balls to the Wall
3       3                         Fast As a Shark
4       4                       Restless and Wild
5       5                    Princess of the Dawn
6       6                   Put The Finger On You
                                                                Composer
1                              Angus Young, Malcolm Young, Brian Johnson
2                                                                   <NA>
3                    F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman
4 F. Baltes, R.A. Smith-Diesel, S. Kaufman, U. Dirkscneider & W. Hoffman
5                                             Deaffy & R.A. Smith-Diesel
6                              Angus Young, Malcolm Young, Brian Johnson
  UnitPrice
1      0.99
2      0.99
3      0.99
4      0.99
5      0.99
6      0.99

Interpretasi: Interpretation: Kolom yang dipilih saja muncul.Only selected columns appear.

TrackId tetap menjadi identitas observasi. Nama komposer yang kosong tidak menghapus track dari hasil, sebab query ini hanya memilih kolom dan tidak memiliki kondisi WHERE.TrackId remains the observation identifier. Missing composer names do not remove tracks because this query only selects columns and contains no WHERE condition.

Contoh 02 · ORDER BY — Mengurutkan berdasarkan albumExample 02 · ORDER BY — Sort by album

Setelah kolom dipilih, urutan hasil dapat diatur agar track dari album yang sama tampil berdekatan. Gunakan AlbumId sebagai kunci pengurutan. ORDER BY tidak mengelompokkan atau meringkas data; jumlah observasi tetap sama.After selecting columns, we can arrange the results so tracks from the same album appear together. Use AlbumId as the sorting key. ORDER BY does not group or summarize data; the number of observations stays the same.

ASC adalah urutan naik (default), DESC adalah urutan turun.ASC means ascending order (default), DESC means descending.

SQL
SELECT Name, Milliseconds, AlbumId
FROM Track
ORDER BY AlbumId;
ILUSTRASI · SUBSET 10 TRACKILLUSTRATION · 10-TRACK SUBSET
NameMillisecondsAlbumId
For Those About To Rock (We Salute You)3437191
Put The Finger On You2056621
Let's Get It Up2339261
Inject The Venom2108341
Snowballed2031021
Evil Walks2634971
Balls to the Wall3425622
Fast As a Shark2306193
Restless and Wild2520513
Princess of the Dawn3754183

Tabel ini memperlihatkan operasi pada 10 track pertama sebagai ilustrasi. Jalankan query pada database Chinook untuk memperoleh hasil lengkap; baris awal hasil database lengkap dapat berbeda.This table illustrates the operation on the first 10 tracks. Run the query on the Chinook database to obtain the full result; the first rows of the full database result may differ.

Pratinjau subset, bukan hasil query seluruh database Chinook. Jalankan kode pada database lengkap untuk mendapatkan hasil aktual.Subset preview, not the full Chinook query result. Run the code on the complete database for actual results.

Interpretasi: Interpretation: AlbumId diurutkan naik.AlbumId is sorted ascending.

Bandingkan urutan AlbumId sebelum dan sesudah query. Jika membutuhkan urutan yang konsisten di dalam album, tambahkan TrackId sebagai kunci kedua.Compare AlbumId ordering before and after the query. If consistent ordering within albums is needed, add TrackId as a secondary key.

Contoh 03 · ORDER BY — Mengurutkan dengan dua kolomExample 03 · ORDER BY — Sort by two columns

Kadang satu variabel pengurutan belum cukup. Jika fokus kita adalah durasi, gunakan Milliseconds DESC sebagai prioritas pertama. Jika dua track memiliki durasi sama, AlbumId ASC menjadi aturan pengurutan kedua.Sometimes one sorting variable is not enough. If duration is the main focus, use Milliseconds DESC as the primary rule. If two tracks have equal durations, AlbumId ASC becomes the secondary ordering rule.

Durasi terbesar ditampilkan dahulu; AlbumId memecahkan seri durasi.Longest durations come first; AlbumId breaks duration ties.

SQL
SELECT Name, Milliseconds, AlbumId
FROM Track
ORDER BY Milliseconds DESC, AlbumId ASC;
ILUSTRASI · SUBSET 10 TRACKILLUSTRATION · 10-TRACK SUBSET
NameMillisecondsAlbumId
Princess of the Dawn3754183
For Those About To Rock (We Salute You)3437191
Balls to the Wall3425622
Evil Walks2634971
Restless and Wild2520513
Let's Get It Up2339261
Fast As a Shark2306193
Inject The Venom2108341
Put The Finger On You2056621
Snowballed2031021

Tabel ini memperlihatkan operasi pada 10 track pertama sebagai ilustrasi. Jalankan query pada database Chinook untuk memperoleh hasil lengkap; baris awal hasil database lengkap dapat berbeda.This table illustrates the operation on the first 10 tracks. Run the query on the Chinook database to obtain the full result; the first rows of the full database result may differ.

Pratinjau subset, bukan hasil query seluruh database Chinook. Jalankan kode pada database lengkap untuk mendapatkan hasil aktual.Subset preview, not the full Chinook query result. Run the code on the complete database for actual results.

Interpretasi: Interpretation: Durasi diurutkan menurun, kemudian AlbumId naik jika durasi sama.Duration is sorted descending, then AlbumId ascending for ties.

Pengurutan tidak menyatakan bahwa durasi menentukan album; AlbumId hanya digunakan ketika durasi sama. Jumlah baris tidak berubah.Sorting does not imply that duration determines album; AlbumId is used only when duration is tied. The row count does not change.

Contoh 04 · DISTINCT — Menampilkan kota unikExample 04 · DISTINCT — List unique cities

Beberapa pelanggan dapat berasal dari kota yang sama. Untuk memperoleh daftar kota, kita tidak perlu menampilkan nama kota berulang kali. DISTINCT membentuk daftar nilai unik dari kolom City tanpa menghitung banyaknya pelanggan per kota; untuk penghitungan diperlukan GROUP BY.Several customers can come from the same city. To obtain a city list, we do not need repeated names. DISTINCT produces unique City values without counting customers per city; counting requires GROUP BY.

DISTINCT menghapus baris duplikat berdasarkan kombinasi kolom yang dipilih.DISTINCT removes duplicate rows based on the selected column combination.

SQL
SELECT DISTINCT City
FROM Customer
ORDER BY City;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
       City
1 Amsterdam
2 Bangalore
3    Berlin
4  Bordeaux
5    Boston
6  Brasília

Interpretasi: Interpretation: Kota yang sama muncul sekali.Each distinct city appears once.

Daftar kota unik berguna untuk mengetahui kategori yang tersedia, tetapi tidak dapat digunakan untuk menentukan kota dengan pelanggan terbanyak tanpa penghitungan tambahan.A distinct city list is useful for identifying available categories, but cannot identify the city with the most customers without further counting.

Contoh 06 · LIMIT — Membatasi hasil menjadi 10 barisExample 06 · LIMIT — Limit results to 10 rows

Saat memeriksa struktur data, mengambil beberapa baris sering kali cukup. LIMIT 10 membatasi hasil yang dikembalikan SQLite menjadi maksimal sepuluh baris. Gunakan ORDER BY TrackId agar jelas sepuluh track mana yang dipilih.When inspecting a data structure, retrieving a few rows is often sufficient. LIMIT 10 restricts the result returned by SQLite to at most ten rows. Use ORDER BY TrackId to make clear which ten tracks are selected.

LIMIT membatasi jumlah baris; ORDER BY memastikan urutan yang dimaksud.LIMIT restricts the row count; ORDER BY specifies the intended ordering.

SQL
SELECT TrackId, Name
FROM Track
ORDER BY TrackId
LIMIT 10;
ILUSTRASI · SUBSET 10 TRACKILLUSTRATION · 10-TRACK SUBSET
TrackIdName
1For Those About To Rock (We Salute You)
2Balls to the Wall
3Fast As a Shark
4Restless and Wild
5Princess of the Dawn
6Put The Finger On You
7Let's Get It Up
8Inject The Venom
9Snowballed
10Evil Walks

Pratinjau subset, bukan hasil query seluruh database Chinook. Jalankan kode pada database lengkap untuk mendapatkan hasil aktual.Subset preview, not the full Chinook query result. Run the code on the complete database for actual results.

Interpretasi: Interpretation: Sepuluh track pertama menurut TrackId.The first ten tracks ordered by TrackId.

Sepuluh baris merupakan hasil yang dibatasi oleh query, bukan jumlah keseluruhan track. Berbeda dengan head(), LIMIT membatasi data sebelum hasil dikirim ke R.The ten rows are a query-limited result, not the total number of tracks. Unlike head(), LIMIT restricts the data before they are sent to R.

Menyaring dataFiltering data

Pemilihan kolom belum cukup ketika hanya sebagian observasi yang relevan. Misalnya, kita ingin menganalisis track dari album tertentu atau transaksi dengan nilai dalam rentang tertentu. SQL menggunakan WHERE untuk menetapkan kondisi yang harus dipenuhi oleh setiap baris. Baris yang tidak memenuhi kondisi tidak muncul pada hasil, tetapi tetap tersimpan dalam database.Selecting columns is not enough when only some observations are relevant. For example, we may want to analyze tracks from a particular album or transactions within a specified value range. SQL uses WHERE to specify conditions that each row must satisfy. Nonmatching rows are excluded from the result, but remain in the database.

Kondisi dapat menggunakan operator perbandingan, kombinasi logika, daftar kategori, rentang numerik, maupun pemeriksaan nilai yang hilang. Sebelum menjalankan query, nyatakan kriteria dalam kalimat biasa; kemudian terjemahkan kriteria tersebut menjadi kondisi SQL.Conditions can use comparison operators, logical combinations, category lists, numerical intervals and missing-value checks. Before running a query, express the criteria in ordinary language, then translate them into SQL conditions.

Contoh 05 · WHERE — Memilih track album 1Example 05 · WHERE — Filter tracks in album 1

Kita akan mencari track yang memenuhi dua syarat sekaligus: berasal dari album 1 dan berdurasi lebih dari 250.000 milidetik. Uji setiap kondisi secara terpisah jika ingin memahami bagaimana AND mempersempit jumlah baris.We will find tracks satisfying two conditions simultaneously: they belong to album 1 and have duration above 250,000 milliseconds. Test each condition separately to understand how AND narrows the result.

AND mensyaratkan kedua kondisi benar; OR cukup salah satu benar.AND requires both conditions to be true; OR requires at least one.

SQL
SELECT Name, Milliseconds, Bytes, AlbumId
FROM Track
WHERE AlbumId = 1 AND Milliseconds > 250000;
ILUSTRASI · SUBSET 10 TRACKILLUSTRATION · 10-TRACK SUBSET
NameMillisecondsBytesAlbumId
For Those About To Rock (We Salute You)343719111703341
Evil Walks26349786112451

Tabel ini memperlihatkan operasi pada 10 track pertama sebagai ilustrasi. Jalankan query pada database Chinook untuk memperoleh hasil lengkap; baris awal hasil database lengkap dapat berbeda.This table illustrates the operation on the first 10 tracks. Run the query on the Chinook database to obtain the full result; the first rows of the full database result may differ.

Pratinjau subset, bukan hasil query seluruh database Chinook. Jalankan kode pada database lengkap untuk mendapatkan hasil aktual.Subset preview, not the full Chinook query result. Run the code on the complete database for actual results.

Interpretasi: Interpretation: Hanya track dengan AlbumId = 1 dan durasi lebih dari 250.000 ms yang lolos.Only tracks with AlbumId = 1 and duration above 250,000 ms remain.

Ubah batas durasi untuk mengamati perubahan jumlah baris yang lolos. Syarat lebih besar bersifat ketat: track dengan durasi tepat 250.000 ms tidak ikut.Change the duration threshold to observe the number of qualifying rows. The greater-than condition is strict: a track lasting exactly 250,000 ms is excluded.

Contoh 07 · BETWEEN — Memilih invoice dalam rentang nilaiExample 07 · BETWEEN — Filter invoices within a range

Untuk menyaring transaksi bernilai antara 14,91 dan 18,86, gunakan BETWEEN pada kolom Total. Berbeda dari dua operator ketat, batas bawah dan batas atas ikut dipertahankan. Hasil diurutkan menurut Total agar rentangnya mudah diperiksa.To filter transactions valued between 14.91 and 18.86, apply BETWEEN to Total. Unlike two strict inequalities, both endpoints are retained. Sort the result by Total to inspect the range easily.

BETWEEN mencakup kedua batas.BETWEEN includes both endpoints.

SQL
SELECT InvoiceId, BillingAddress, Total
FROM Invoice
WHERE Total BETWEEN 14.91 AND 18.86
ORDER BY Total;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
  InvoiceId                       BillingAddress Total
1       193                     Berger Straße 10 14.91
2       103                162 E Superior Street 15.86
3       208                     Ullevålsveien 14 15.86
4       306                        Klanova 9/506 16.86
5       313                     68, Rue Jouvence 16.86
6        88                      Calle Lira, 198 17.91
7        89 Rotenturmstraße 4, 1010 Innere Stadt 18.86
8       201                319 N. Frances Street 18.86

Interpretasi: Interpretation: Kedua batas termasuk dalam rentang.Both endpoints are included.

Periksa Total pada baris awal dan akhir. Rentang ini menggambarkan nilai invoice, bukan jumlah pelanggan atau jumlah produk yang dibeli.Inspect Total in the first and last rows. This range describes invoice value, not the number of customers or products purchased.

Contoh 08 · IN — Memilih tipe media 1 dan 2Example 08 · IN — Select media types 1 and 2

Jika beberapa kategori diperbolehkan, kita dapat menuliskan kondisi OR berulang atau menggunakan IN. Pada contoh ini, MediaTypeId harus bernilai 1 atau 2. IN lebih ringkas terutama ketika daftar kategori yang dipilih semakin panjang.If multiple categories are allowed, we can repeat OR conditions or use IN. Here, MediaTypeId must equal 1 or 2. IN is more concise, particularly as the list of selected categories grows.

IN memeriksa apakah nilai terdapat dalam daftar.IN checks whether a value occurs in a list.

SQL
SELECT TrackId, Name, MediaTypeId
FROM Track
WHERE MediaTypeId IN (1, 2)
ORDER BY Name ASC;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
  TrackId                                                       Name
1    3027                                                       "40"
2    3412 "Eine Kleine Nachtmusik" Serenade In G, K. 525: I. Allegro
3     109                                                    #1 Zero
4    3254                                                   #9 Dream
5     602                                            'Round Midnight
6    1833                                 (Anesthesia) Pulling Teeth
  MediaTypeId
1           1
2           2
3           1
4           2
5           1
6           1

Interpretasi: Interpretation: Hanya media tipe 1 dan 2.Only media types 1 and 2.

MediaTypeId merupakan key kategori, bukan ukuran kualitas media. Untuk membaca nama tipe media, gabungkan Track dengan MediaType berdasarkan MediaTypeId.MediaTypeId is a category key, not a media-quality measure. To read media type names, join Track with MediaType using MediaTypeId.

Contoh 09 · IS NULL — Mendeteksi komposer kosongExample 09 · IS NULL — Detect missing composers

Tidak semua track memiliki informasi komposer. Sebelum analisis, kita perlu membedakan nilai yang hilang dari teks kosong atau angka nol. Pada SQL, pemeriksaan nilai yang hilang dilakukan menggunakan IS NULL; ketika hasil dipindahkan ke R, nilai ini biasanya direpresentasikan sebagai NA.Not all tracks have composer information. Before analysis, distinguish missing values from empty strings or zero. SQL checks missing values using IS NULL; when results are transferred to R, these values are typically represented as NA.

NULL menandakan nilai yang tidak diketahui; gunakan IS NULL, bukan = NULL. Dalam R hasil SQL NULL biasanya NA.NULL represents an unknown value; use IS NULL, not = NULL. In R, SQL NULL usually becomes NA.

SQL
SELECT TrackId, Name, Composer
FROM Track
WHERE Composer IS NULL
ORDER BY Name ASC;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
  TrackId                                    Name Composer
1    2918                                     "?"     <NA>
2    3254                                #9 Dream     <NA>
3    3045 (I Can't Help) Falling In Love With You     <NA>
4    2869                            ...And Found     <NA>
5    2906                       ...In Translation     <NA>
6    3166                                    .07%     <NA>

Interpretasi: Interpretation: Composer NULL ditampilkan sebagai NA di R.NULL composers display as NA in R.

Hasil dapat digunakan untuk mengaudit kelengkapan informasi. Untuk mengambil track dengan komposer tersedia, gunakan IS NOT NULL; keputusan penanganan nilai hilang bergantung pada kebutuhan analisis.The result can be used to audit information completeness. To retrieve tracks with available composer information, use IS NOT NULL; missing-value treatment depends on the analytical task.

Coba ubah AlbumId dan batas durasi, kemudian perhatikan perubahan WHERE dan jumlah baris. Ubah ASC menjadi DESC; jumlah baris yang lolos tetap, tetapi posisi baris berubah.Change AlbumId and the duration threshold, then observe WHERE and the number of rows. Switch ASC to DESC; the number of qualifying rows stays the same but their order changes.

INTERACTIVE 02 · SQL QUERY EXPLORER

Ubah kondisi dan periksa hasilChange conditions and inspect results

Simulasi menggunakan enam track pertama. Hasil berlaku pada subset tersebut, bukan seluruh Chinook.This simulation uses the first six tracks. Results apply to that subset, not the entire Chinook database.

Agregasi dan pengelompokanAggregation and grouping

Tidak semua pertanyaan analisis memerlukan data pada tingkat observasi individual. Untuk mengetahui album dengan track terbanyak, kita tidak perlu menampilkan seluruh 3.503 track sekaligus. Kita dapat meringkas tabel Track menjadi satu baris per album. GROUP BY menentukan kelompok, sedangkan fungsi agregasi menghitung ringkasan untuk setiap kelompok.Not every analytical question requires individual observations. To identify the album with the most tracks, we do not need to display all 3,503 tracks at once. We can summarize Track into one row per album. GROUP BY defines groups, while aggregate functions calculate a summary for each group.

Perhatikan perubahan unit observasi: sebelum agregasi, satu baris berarti satu track; setelah agregasi, satu baris berarti satu album. Pada enam track pertama, album 1 muncul dua kali, album 2 satu kali, dan album 3 tiga kali. Contoh kecil ini cukup untuk melihat cara COUNT bekerja sebelum kita menjalankan query pada seluruh database.Notice the change in observational unit: before aggregation, a row represents a track; afterward, a row represents an album. Among the first six tracks, album 1 appears twice, album 2 once and album 3 three times. This small example makes the behavior of COUNT visible before running the query on the full database.

Agregasi meringkas sejumlah observasi menjadi satu nilai per kelompok. COUNT menghitung, SUM menjumlahkan, AVG menghitung rata-rata, MIN dan MAX mengambil nilai terkecil dan terbesar. COUNT(*) menghitung semua baris, sedangkan COUNT(kolom) mengabaikan NULL.Aggregation summarizes observations into one value per group. COUNT counts, SUM adds, AVG calculates the mean, and MIN/MAX find the smallest/largest values. COUNT(*) counts all rows, while COUNT(column) ignores NULL.

Pada ilustrasi enam track, ubah batas minimum jumlah track. Amati bahwa HAVING mengurangi jumlah kelompok yang ditampilkan tanpa mengubah jumlah track yang dihitung di dalam setiap kelompok.In the six-track illustration, change the minimum track count. Observe that HAVING reduces the displayed groups without changing the count within each group.

INTERACTIVE 03 · GROUP BY & HAVING

Lihat proses dari baris ke kelompokSee the transformation from rows to groups

Ilustrasi manual: enam track pertama membentuk tiga kelompok dengan jumlah 2, 1, dan 3.Manual illustration: six tracks form three groups with counts of 2, 1 and 3.

Contoh 10 · GROUP BY — Menghitung jumlah track per albumExample 10 · GROUP BY — Count tracks per album

Terapkan proses pengelompokan pada keseluruhan Track. COUNT(TrackId) menghitung track pada setiap AlbumId, kemudian AS N memberi nama ringkasan agar mudah digunakan dalam pengurutan maupun visualisasi.Apply grouping to the entire Track table. COUNT(TrackId) counts tracks for each AlbumId, and AS N names the summary for convenient sorting and visualization.

GROUP BY membentuk satu kelompok untuk setiap AlbumId; COUNT(TrackId) menghitung nilai TrackId yang tidak NULL.GROUP BY forms one group for each AlbumId; COUNT(TrackId) counts non-NULL TrackId values.

SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
GROUP BY AlbumId
ORDER BY N DESC;
CUPLIKAN HASIL QUERYQUERY RESULT EXCERPT
  AlbumId  N
1     141 57
2      23 34
3      73 30
4     229 26
5     230 25
6     251 25

Interpretasi: Interpretation: Jumlah track dihitung untuk setiap album.Track count is computed for each album.

Album 141 memiliki 57 track, sedangkan album 23 memiliki 34. Perbandingan ini menyatakan banyaknya track yang tercatat, bukan banyaknya penjualan.Album 141 has 57 tracks, while album 23 has 34. This comparison reflects recorded track counts, not sales volume.

Contoh 11 · HAVING — Memilih hasil kelompok album 1Example 11 · HAVING — Filter the group for album 1

Sesudah ringkasan album terbentuk, kita dapat memilih kelompok yang dibutuhkan. HAVING dapat memeriksa nilai kelompok maupun hasil agregasi. Untuk AlbumId = 1, WHERE sebelum pengelompokan memberikan ringkasan yang sama; tetapi kondisi seperti COUNT(TrackId) >= 25 harus diterapkan setelah agregasi.Once album summaries are formed, we can select the desired groups. HAVING can inspect grouping values or aggregate results. For AlbumId = 1, WHERE before grouping gives the same summary; however, a condition such as COUNT(TrackId) >= 25 must be applied after aggregation.

WHERE menyaring baris sebelum pengelompokan; HAVING menyaring kelompok setelah pengelompokan.WHERE filters rows before grouping; HAVING filters groups after grouping.

SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
GROUP BY AlbumId
HAVING AlbumId = 1;
HASIL · ALBUM 1RESULT · ALBUM 1
AlbumIdN
110

Interpretasi: Interpretation: Album 1 mempunyai 10 track dalam ringkasan kelompok.Album 1 has 10 tracks in the group summary.

Jika ingin memilih album berdasarkan jumlah track, letakkan syarat pada COUNT(TrackId), bukan pada TrackId individual. Dengan demikian unit penyaringan adalah kelompok album.To select albums by their track counts, apply the condition to COUNT(TrackId), not individual TrackId values. The filtering unit is then the album group.

Alternatif pada contoh 11: menyaring AlbumId sebelum agregasi memberikan hasil yang sama. Untuk menyaring berdasarkan jumlah track, gunakan HAVING COUNT(TrackId).Alternative for example 11: filtering AlbumId before aggregation gives the same result. To filter by track count, use HAVING COUNT(TrackId).

SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
WHERE AlbumId = 1
GROUP BY AlbumId;
SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
GROUP BY AlbumId
HAVING COUNT(TrackId) >= 25
ORDER BY N DESC;

Karena AlbumId adalah kolom pengelompokan, kondisi yang sama dapat diterapkan lebih awal menggunakan WHERE. Bandingkan kedua query ini, lalu ubah syarat menjadi jumlah track minimal 25 untuk melihat kegunaan HAVING pada hasil agregasi.Because AlbumId is a grouping column, the same condition can be applied earlier using WHERE. Compare both queries, then change the condition to a minimum track count of 25 to see the use of HAVING on aggregate results.

SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
WHERE AlbumId = 1
GROUP BY AlbumId;
SQL
SELECT AlbumId, COUNT(TrackId) AS N
FROM Track
GROUP BY AlbumId
HAVING COUNT(TrackId) >= 25
ORDER BY N DESC;

Membuat tabel dan ekspor CSVCreating and exporting tables

Hasil SELECT bersifat sementara: database mengembalikan tabel hasil tanpa menyimpan tabel baru secara otomatis. Apabila hasil tersebut akan digunakan kembali, kita dapat menyimpannya sebagai tabel melalui CREATE TABLE AS, atau mengekspornya menjadi CSV agar dapat digunakan pada perangkat lunak lain.SELECT results are temporary: the database returns a result table without automatically storing a new table. If the result will be reused, we can save it through CREATE TABLE AS or export it as CSV for use in other software.

Pada contoh ini kita menyimpan track dengan MediaTypeId 1 dan 2. Perintah CREATE berbeda dari SELECT karena mengubah struktur database. Gunakan salinan Chinook yang dapat ditulis untuk latihan ini dan simpan perubahan melalui Write Changes di DB Browser jika diperlukan.In this example, we save tracks with MediaTypeId 1 and 2. CREATE differs from SELECT because it modifies the database structure. Use a writable copy of Chinook for this exercise and save changes through Write Changes in DB Browser when needed.

CREATE TABLE AS menyimpan hasil query sebagai tabel baru. Gunakan nama yang belum ada. Jika Track_Media12 sudah tersedia, pilih nama lain atau gunakan salinan database yang bersih; jangan menghapus tabel asli tanpa sengaja.CREATE TABLE AS saves query results as a new table. Use an unused name. If Track_Media12 already exists, choose another name or a clean database copy; do not accidentally delete original tables.

SQL
CREATE TABLE Track_Media12 AS
SELECT TrackId, Name, MediaTypeId
FROM Track
WHERE MediaTypeId IN (1, 2)
ORDER BY Name ASC;

Untuk melakukan perubahan database dari R gunakan dbExecute(), bukan dbGetQuery(). Contoh berikut menyimpan hasil dengan nama berbeda; jalankan pada database salinan setelah bagian 08.Use dbExecute(), rather than dbGetQuery(), for database changes in R. The example below saves results under a different name; run on a database copy after section 08.

R
stopifnot(file.exists("Chinook_Sqlite.sqlite"))
work_db <- tempfile(fileext = ".sqlite")
stopifnot(file.copy("Chinook_Sqlite.sqlite", work_db))
write_con <- dbConnect(RSQLite::SQLite(), work_db)
dbExecute(write_con, "
  CREATE TABLE Track_Media12_R AS
  SELECT TrackId, Name, MediaTypeId
  FROM Track WHERE MediaTypeId IN (1, 2)
  ORDER BY Name ASC;
")
dbListTables(write_con)
dbDisconnect(write_con)
unlink(work_db)

Ekspor melalui DB BrowserExport through DB Browser

Langkah 1. Klik File.Step 1. Click File.
CSV export — step 1
Ekspor CSV — langkah 1CSV export — step 1
Langkah 2. Klik Export.Step 2. Click Export.
CSV export — step 2
Ekspor CSV — langkah 2CSV export — step 2
Langkah 3. Klik Table(s) as CSV file…Step 3. Click Table(s) as CSV file…
CSV export — step 3
Ekspor CSV — langkah 3CSV export — step 3
CSV export — step 3
Ekspor CSV — langkah 3CSV export — step 3
Langkah 4. Cari Track_Media12, gulir bila perlu, lalu klik Save.Step 4. Find Track_Media12, scroll if necessary, and click Save.
CSV export — step 4
Ekspor CSV — langkah 4CSV export — step 4
Langkah 5. Pilih folder tujuan, misalnya New folder(2), lalu klik Select Folder.Step 5. Choose the destination folder, e.g. New folder(2), and click Select Folder.
CSV export — step 5
Ekspor CSV — langkah 5CSV export — step 5
Langkah 6. Klik OK.Step 6. Click OK.
CSV export — step 6
Ekspor CSV — langkah 6CSV export — step 6

Di R, hasil SELECT dapat langsung ditulis sebagai CSV tanpa membuat tabel baru.In R, SELECT results can be written directly to CSV without creating a new table.

R
track_media12 <- dbGetQuery(chinook, "
 SELECT TrackId, Name, MediaTypeId FROM Track
 WHERE MediaTypeId IN (1, 2) ORDER BY Name
")
write.csv(track_media12, "Track_Media12.csv", row.names = FALSE)

Menghubungkan database ke RStudioConnecting the database to RStudio

Pada tahap sebelumnya kita berinteraksi dengan SQLite melalui DB Browser. Untuk melakukan pengolahan dan visualisasi secara berulang, lebih praktis menghubungkan database tersebut langsung ke RStudio. DBI menyediakan fungsi koneksi dan pengiriman query, sedangkan RSQLite merupakan driver yang memungkinkan R berkomunikasi dengan SQLite.Previously, we interacted with SQLite through DB Browser. For repeated data processing and visualization, it is more practical to connect the database directly to RStudio. DBI provides connection and query functions, while RSQLite is the driver that lets R communicate with SQLite.

Buka project praktikum, pastikan file SQLite berada pada working directory, lalu instal dan aktifkan package yang diperlukan. Jalankan kode koneksi sebelum menggunakan tab R pada contoh SQL. Koneksi ini akan digunakan kembali sampai seluruh pengolahan dan visualisasi selesai.Open the practicum project, ensure the SQLite file is in the working directory, then install and load the required packages. Run the connection code before using the R tabs in the SQL examples. This connection will be reused until data processing and visualization are complete.

Package tidyverse menyediakan dplyr untuk manipulasi dan ggplot2 untuk visualisasi. DBI menyediakan antarmuka database, RSQLite menyediakan driver SQLite, dan dbplyr menerjemahkan operasi dplyr menjadi SQL. Instalasi hanya diperlukan sekali; panggil library pada setiap sesi baru.The tidyverse package provides dplyr for manipulation and ggplot2 for visualization. DBI provides the database interface, RSQLite the SQLite driver, and dbplyr translates dplyr operations into SQL. Install packages only once, then load libraries in each new session.

R
install.packages(c("tidyverse", "DBI", "RSQLite", "dbplyr"))
R
library(tidyverse)
library(DBI)
library(RSQLite)
library(dbplyr)

Pesan package dapat berbeda menurut versi R. Tidak semua pesan saat library() berarti error.Package messages vary by R version. Not all library() messages are errors.

Koneksi dan validasiConnection and validation

Fungsi file.exists() memeriksa apakah path menunjuk pada file yang tersedia. Setelah itu, dbConnect() membuka koneksi SQLite. dbIsValid() digunakan untuk memastikan objek koneksi masih dapat digunakan sebelum mengirim query. Jika file tidak ditemukan, periksa getwd() atau sesuaikan path; jangan membuka database kosong secara tidak sengaja.file.exists() checks whether the path points to an available file. Then dbConnect() opens a SQLite connection. dbIsValid() confirms that the connection object is usable before submitting queries. If the file is not found, inspect getwd() or adjust the path; avoid accidentally opening an empty database.

Simpan file SQLite di folder project. Periksa working directory dan keberadaan file; stop jika file tidak ditemukan untuk menghindari pembuatan database kosong.Save the SQLite file in the project folder. Check the working directory and file existence; stop if the file is missing to avoid creating an empty database.

R
db_path <- "Chinook_Sqlite.sqlite"

file.exists(db_path)
OUTPUT RR OUTPUT
[1] TRUE
R
stopifnot(file.exists(db_path))
chinook <- dbConnect(
  RSQLite::SQLite(),
  db_path,
  flags = RSQLite::SQLITE_RO
)

dbIsValid(chinook)
OUTPUT RR OUTPUT
[1] TRUE

Interpretasi: Interpretation: TRUE menunjukkan bahwa file tersedia dan koneksi valid. Koneksi utama hanya untuk membaca; gunakan salinan terpisah untuk perubahan tabel.TRUE confirms file existence and a valid connection. The main connection is read-only; use a separate copy for table changes.

Jangan lanjutkan query bila pemeriksaan menghasilkan FALSE. Pastikan file dan nama tabel benar, lalu buat koneksi ulang sebelum mengambil data.Do not proceed with queries if the check returns FALSE. Verify the file and table names, then reconnect before retrieving data.

TRUE menunjukkan koneksi valid. Track_Media12/13/14 adalah tabel tambahan yang tercatat pada database yang telah digunakan untuk latihan, sehingga mungkin tidak ada pada salinan awal mahasiswa.TRUE means the connection is valid. Track_Media12/13/14 are extra tables recorded in the database previously used for exercises and may not exist in a student’s initial copy.

SQL dan manipulasi database di RSQL and database manipulation in R

Setelah koneksi terbentuk, query yang semula ditulis pada DB Browser dapat dikirim dari R menggunakan dbGetQuery(). Fungsi ini menerima objek koneksi dan string SQL, menjalankan query di database, lalu mengembalikan hasil sebagai data.frame. Objek tersebut dapat diperiksa, dimanipulasi, dan divisualisasikan menggunakan fungsi R.Once the connection is established, the queries previously entered in DB Browser can be submitted from R using dbGetQuery(). The function takes a connection object and a SQL string, executes the query in the database, and returns a data.frame. The object can then be inspected, manipulated and visualized in R.

Untuk database berukuran besar, sering kali lebih efisien menyusun ringkasan di database terlebih dahulu daripada mengambil seluruh tabel. Oleh karena itu, kita juga menggunakan tbl() dan dbplyr untuk membangun query secara bertahap. Perhatikan perbedaan antara objek yang masih merujuk pada database dan objek data lokal yang telah diperoleh melalui collect().For large databases, it is often more efficient to summarize data in the database rather than retrieve the entire table. We therefore also use tbl() and dbplyr to build a query progressively. Pay attention to the difference between an object that still refers to the database and a local data object retrieved through collect().

Memilih kolom dan memeriksa strukturSelect columns and inspect structure

Mulailah dengan empat kolom dari Track yang sudah kita kenal. Hasil disimpan sebagai track_data. Periksa beberapa baris menggunakan head(), kemudian lihat tipe variabel dan dimensi objek menggunakan glimpse(). Kedua langkah ini penting sebelum menentukan jenis analisis.Start with four familiar columns from Track. Store the result as track_data. Inspect several rows with head(), then check variable types and dimensions using glimpse(). Both steps matter before choosing an analysis.

R
track_data <- dbGetQuery(
  chinook,
  "
  SELECT TrackId, Name, Composer, UnitPrice
  FROM Track;
  "
)

head(track_data)
OUTPUT RR OUTPUT
  TrackId                                    Name
1       1 For Those About To Rock (We Salute You)
2       2                       Balls to the Wall
3       3                         Fast As a Shark
4       4                       Restless and Wild
5       5                    Princess of the Dawn
6       6                   Put The Finger On You
                                                                Composer
1                              Angus Young, Malcolm Young, Brian Johnson
2                                                                   <NA>
3                    F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman
4 F. Baltes, R.A. Smith-Diesel, S. Kaufman, U. Dirkscneider & W. Hoffman
5                                             Deaffy & R.A. Smith-Diesel
6                              Angus Young, Malcolm Young, Brian Johnson
  UnitPrice
1      0.99
2      0.99
3      0.99
4      0.99
5      0.99
6      0.99

Interpretasi: Interpretation: head() menampilkan enam baris pertama hasil query, bukan seluruh data.head() displays the first six query rows, not the entire dataset.

Periksa tipe TrackId dan UnitPrice sebelum analisis numerik; kolom nama dan komposer merupakan atribut teks. head() hanya cuplikan, sehingga jumlah baris objek harus diperiksa secara terpisah.Check the types of TrackId and UnitPrice before numerical analysis; name and composer are text attributes. head() is only a preview, so inspect the object row count separately.

Seluruh kolom, 10 observasiAll columns, 10 observations

Jika nama seluruh kolom belum diketahui, SELECT * dapat digunakan untuk peninjauan awal. LIMIT menjaga ukuran hasil agar tetap kecil. Untuk pemodelan atau pengolahan berikutnya, pilih kembali kolom yang memang diperlukan.If all column names are not yet known, SELECT * can be used for initial inspection. LIMIT keeps the result small. For modeling or further processing, select only the columns actually needed.

R
track_all <- dbGetQuery(
  chinook,
  "
  SELECT *
  FROM Track
  LIMIT 10;
  "
)

track_all
OUTPUT RR OUTPUT
   TrackId                                    Name AlbumId MediaTypeId GenreId
1        1 For Those About To Rock (We Salute You)       1           1       1
2        2                       Balls to the Wall       2           2       1
3        3                         Fast As a Shark       3           2       1
4        4                       Restless and Wild       3           2       1
5        5                    Princess of the Dawn       3           2       1
6        6                   Put The Finger On You       1           1       1
7        7                         Let's Get It Up       1           1       1
8        8                        Inject The Venom       1           1       1
9        9                              Snowballed       1           1       1
10      10                              Evil Walks       1           1       1
                                                                 Composer
1                               Angus Young, Malcolm Young, Brian Johnson
2                                                                    <NA>
3                     F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman
4  F. Baltes, R.A. Smith-Diesel, S. Kaufman, U. Dirkscneider & W. Hoffman
5                                              Deaffy & R.A. Smith-Diesel
6                               Angus Young, Malcolm Young, Brian Johnson
7                               Angus Young, Malcolm Young, Brian Johnson
8                               Angus Young, Malcolm Young, Brian Johnson
9                               Angus Young, Malcolm Young, Brian Johnson
10                              Angus Young, Malcolm Young, Brian Johnson
   Milliseconds    Bytes UnitPrice
1        343719 11170334      0.99
2        342562  5510424      0.99
3        230619  3990994      0.99
4        252051  4331779      0.99
5        375418  6290521      0.99
6        205662  6713451      0.99
7        233926  7636561      0.99
8        210834  6852860      0.99
9        203102  6599424      0.99
10       263497  8611245      0.99

Interpretasi: Interpretation: Sepuluh baris dan sembilan kolom ditampilkan; tanpa ORDER BY urutan tidak dijamin.Ten rows and nine columns are displayed; without ORDER BY, order is not guaranteed.

SELECT * bermanfaat saat eksplorasi awal, tetapi pengambilan seluruh kolom tidak perlu jika analisis hanya menggunakan beberapa variabel.SELECT * is helpful for initial exploration, but retrieving every column is unnecessary when analysis uses only a few variables.

Track dalam album 1Tracks in album 1

Sekarang ambil data track dari satu album menggunakan kondisi WHERE. Berbeda dari contoh dua kondisi sebelumnya, kita tidak membatasi durasi sehingga seluruh track milik album 1 dapat diperiksa.Now retrieve tracks from one album using WHERE. Unlike the previous two-condition example, we do not restrict duration, so all tracks belonging to album 1 can be inspected.

R
album_1 <- dbGetQuery(
  chinook,
  "
  SELECT TrackId, Name, AlbumId, Milliseconds
  FROM Track
  WHERE AlbumId = 1;
  "
)

album_1
OUTPUT RR OUTPUT
   TrackId                                    Name AlbumId Milliseconds
1        1 For Those About To Rock (We Salute You)       1       343719
2        6                   Put The Finger On You       1       205662
3        7                         Let's Get It Up       1       233926
4        8                        Inject The Venom       1       210834
5        9                              Snowballed       1       203102
6       10                              Evil Walks       1       263497
7       11                                  C.O.D.       1       199836
8       12                      Breaking The Rules       1       263288
9       13                Night Of The Long Knives       1       205688
10      14                              Spellbound       1       270863

Interpretasi: Interpretation: Seluruh sepuluh track pada album 1 memenuhi kondisi.All ten tracks in album 1 match the condition.

Karena tidak ada syarat durasi, track pendek maupun panjang tetap dipertahankan. Gunakan nrow(album_1) jika ingin memeriksa jumlah observasi hasil.Because there is no duration condition, short and long tracks are both retained. Use nrow(album_1) to inspect the number of resulting observations.

Track berdurasi panjangLong tracks

Query dari R tidak terbatas pada satu jenis seleksi. Pada tab berikut, kita mengurutkan track berdurasi panjang, mengambil kota unik, memilih invoice dalam rentang tertentu, menyaring tipe media, dan memeriksa nilai komposer yang hilang. Setiap hasil disimpan dalam objek berbeda agar mudah diperiksa kembali.Queries from R are not limited to one kind of selection. In the tabs below, we sort long tracks, retrieve unique cities, select invoices in an interval, filter media types and check missing composers. Each result is stored in a separate object for later inspection.

R
long_tracks <- dbGetQuery(
  chinook,
  "
  SELECT TrackId, Name, Milliseconds
  FROM Track
  WHERE Milliseconds > 250000
  ORDER BY Milliseconds DESC;
  "
)

head(long_tracks)
OUTPUT RR OUTPUT
  TrackId                        Name Milliseconds
1    2820      Occupation / Precipice      5286953
2    3224     Through a Looking Glass      5088838
3    3244 Greetings from Earth, Pt. 1      2960293
4    3242     The Man With Nine Lives      2956998
5    3227 Battlestar Galactica, Pt. 2      2956081
6    3226 Battlestar Galactica, Pt. 1      2952702

Interpretasi: Interpretation: Track terlama berada pada baris awal setelah diurutkan menurun; durasi dinyatakan dalam milidetik.The longest tracks appear first after descending sort; duration is in milliseconds.

Durasi yang besar dapat berasal dari jenis media berbeda. Gunakan filter tambahan bila ingin membandingkan hanya satu tipe media.Long durations can occur across media types. Add a filter if comparing only one media type.

Agregasi albumAlbum aggregation

Untuk visualisasi jumlah track per album, sebaiknya agregasi dilakukan di SQLite terlebih dahulu. Dengan cara ini, R menerima tabel ringkasan berisi AlbumId dan N, bukan seluruh atribut track. Periksa nama kolom dan struktur album_summary sebelum menggunakan ggplot2.For a visualization of track counts by album, aggregate in SQLite first. This way R receives a summary table containing AlbumId and N rather than every track attribute. Inspect column names and the structure of album_summary before using ggplot2.

R
album_summary <- dbGetQuery(
  chinook,
  "
  SELECT AlbumId,
         COUNT(TrackId) AS N
  FROM Track
  GROUP BY AlbumId
  ORDER BY N DESC;
  "
)

head(album_summary)
OUTPUT RR OUTPUT
  AlbumId  N
1     141 57
2      23 34
3      73 30
4     229 26
5     230 25
6     251 25
R
names(album_summary)
glimpse(album_summary)
OUTPUT RR OUTPUT
[1] "AlbumId" "N"
Rows: 347
Columns: 2
$ AlbumId <int> 141, 23, 73, 229, 230, 251, 83, 231, 253, 24, 228, 255, 51, 22…
$ N       <int> 57, 34, 30, 26, 25, 25, 24, 24, 24, 23, 23, 23, 22, 22, 22, 21…

Interpretasi: Interpretation: Album 141 memiliki 57 track; 347 album merupakan kelompok, bukan jumlah track.Album 141 has 57 tracks; 347 albums are groups, not the number of tracks.

Objek album_summary sudah berada pada tingkat album. Karena itu gunakan N sebagai nilai tinggi batang dalam geom_col(), bukan menghitung ulang jumlah baris per AlbumId.album_summary is already at the album level. Therefore use N as bar height in geom_col(), rather than counting rows per AlbumId again.

Lazy table dan data.frameLazy tables and data.frames

Bayangkan tabel Customer jauh lebih besar daripada contoh Chinook. Menyalin seluruh tabel ke R hanya untuk menghitung satu statistik dapat membebani memori. tbl() menyediakan pendekatan berbeda: objek R menyimpan referensi dan rencana query, sedangkan data tetap berada di SQLite sampai diperlukan.Imagine that Customer is much larger than the Chinook example. Copying the entire table into R merely to calculate one statistic can consume unnecessary memory. tbl() provides a different approach: an R object stores a reference and a query plan while data remain in SQLite until needed.

tbl() membuat referensi tabel pada database. Operasi dplyr terhadap lazy table menyusun query, tidak otomatis memindahkan semua baris ke R. Menampilkan preview dapat memicu query terbatas. collect() mengambil hasil; as.data.frame() juga dapat mengubahnya menjadi data.frame.tbl() creates a reference to a database table. dplyr operations on a lazy table construct queries without automatically copying all rows to R. Printing a preview may trigger a limited query. collect() retrieves results; as.data.frame() can also convert them to a data.frame.

R
customer <- tbl(
  chinook,
  "Customer"
)

customer
OUTPUT RR OUTPUT
# A query:  ?? x 13
# Database: sqlite 3.53.3 [Chinook_Sqlite.sqlite]
   CustomerId FirstName LastName  Company Address City  State Country PostalCode
        <int> <chr>     <chr>     <chr>   <chr>   <chr> <chr> <chr>   <chr>
 1          1 Luís      Gonçalves Embrae… Av. Br… São … SP    Brazil  12227-000
 2          2 Leonie    Köhler    <NA>    Theodo… Stut… <NA>  Germany 70174
 3          3 François  Tremblay  <NA>    1498 r… Mont… QC    Canada  H2G 1A7
 4          4 Bjørn     Hansen    <NA>    Ullevå… Oslo  <NA>  Norway  0171
 5          5 František Wichterl… JetBra… Klanov… Prag… <NA>  Czech … 14700
 6          6 Helena    Holý      <NA>    Rilská… Prag… <NA>  Czech … 14300
 7          7 Astrid    Gruber    <NA>    Rotent… Vien… <NA>  Austria 1010
 8          8 Daan      Peeters   <NA>    Grétry… Brus… <NA>  Belgium 1000
 9          9 Kara      Nielsen   <NA>    Sønder… Cope… <NA>  Denmark 1720
10         10 Eduardo   Martins   Woodst… Rua Dr… São … SP    Brazil  01007-010
R
class(customer)
OUTPUT RR OUTPUT
[1] "tbl_SQLiteConnection" "tbl_dbi"              "tbl_sql"
[4] "tbl_lazy"             "tbl"
R
glimpse(customer)
OUTPUT RR OUTPUT
Rows: ??
Columns: 13
$ CustomerId   <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17…
$ FirstName    <chr> "Luís", "Leonie", "François", "Bjørn", "František", "Hele…
$ LastName     <chr> "Gonçalves", "Köhler", "Tremblay", "Hansen", "Wichterlová…
$ Company      <chr> "Embraer - Empresa Brasileira de Aeronáutica S.A.", NA, N…
$ Address      <chr> "Av. Brigadeiro Faria Lima, 2170", "Theodor-Heuss-Straße …
$ City         <chr> "São José dos Campos", "Stuttgart", "Montréal", "Oslo", "…
$ State        <chr> "SP", NA, "QC", NA, NA, NA, NA, NA, NA, "SP", "SP", "RJ",…
$ Country      <chr> "Brazil", "Germany", "Canada", "Norway", "Czech Republic"…
$ PostalCode   <chr> "12227-000", "70174", "H2G 1A7", "0171", "14700", "14300"…
$ Phone        <chr> "+55 (12) 3923-5555", "+49 0711 2842222", "+1 (514) 721-4…
$ Fax          <chr> "+55 (12) 3923-5566", NA, NA, NA, "+420 2 4172 5555", NA,…
$ Email        <chr> "luisg@embraer.com.br", "leonekohler@surfeu.de", "ftrembl…
$ SupportRepId <int> 3, 5, 3, 4, 4, 5, 5, 4, 4, 4, 5, 3, 4, 5, 3, 4, 5, 3, 3, …
R
object.size(customer)
OUTPUT RR OUTPUT
8384 bytes

Interpretasi: Interpretation: tbl() menyimpan referensi, bukan seluruh data. Preview dapat menjalankan query terbatas.tbl() stores a reference rather than all rows. A preview may execute a limited query.

Ukuran objek yang ditunjukkan hanya ukuran objek R. Lazy query tetap dapat menjalankan query untuk preview atau metadata; keuntungannya adalah tidak perlu mengambil semua data untuk setiap operasi.The displayed object size measures only the R object. A lazy query may still execute queries for previews or metadata; its benefit is avoiding retrieval of all data for every operation.

Klik setiap tahap untuk melihat kapan R hanya menyimpan referensi, kapan sintaks diterjemahkan menjadi SQL, dan kapan hasil dipindahkan ke memori R.Click each stage to see when R stores only a reference, when syntax is translated into SQL, and when results are transferred into R memory.

INTERACTIVE 04 · LAZY EVALUATION

Di mana data diproses?Where is the data processed?

Lazy table 8,384 bytes
Local data.frame 39,176 bytes

Contoh hasil object.size(); ukuran objek dapat berbeda antarversi R dan bukan total memori database.Example object.size() results; object sizes may vary across R versions and do not represent total database memory.

Menghitung rata-rata invoice dengan dbplyrCalculate average invoice with dbplyr

Kita ingin mengetahui rata-rata nilai invoice menurut negara penagihan. Karena satu baris Invoice adalah satu transaksi, mean(Total) menghitung rata-rata per transaksi dalam masing-masing BillingCountry. Susun operasi menggunakan group_by() dan summarize(), lihat SQL yang dibentuk, lalu ambil hasil ringkasannya ke R.We want the average invoice value by billing country. Because each Invoice row is a transaction, mean(Total) calculates the mean per transaction within each BillingCountry. Build the operation with group_by() and summarize(), inspect the generated SQL, then retrieve the summary into R.

R
invoice <- tbl(
  chinook,
  "Invoice"
)

glimpse(invoice)
OUTPUT RR OUTPUT
Rows: ??
Columns: 9
$ InvoiceId         <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1…
$ CustomerId        <int> 2, 4, 8, 14, 23, 37, 38, 40, 42, 46, 52, 2, 16, 17, …
$ InvoiceDate       <chr> "2009-01-01 00:00:00", "2009-01-02 00:00:00", "2009-…
$ BillingAddress    <chr> "Theodor-Heuss-Straße 34", "Ullevålsveien 14", "Grét…
$ BillingCity       <chr> "Stuttgart", "Oslo", "Brussels", "Edmonton", "Boston…
$ BillingState      <chr> NA, NA, NA, "AB", "MA", NA, NA, NA, NA, "Dublin", NA…
$ BillingCountry    <chr> "Germany", "Norway", "Belgium", "Canada", "USA", "Ge…
$ BillingPostalCode <chr> "70174", "0171", "1000", "T6G 2C7", "2113", "60316",…
$ Total             <dbl> 1.98, 3.96, 5.94, 8.91, 13.86, 0.99, 1.98, 1.98, 3.9…
R
invoice_country <- invoice %>%
  group_by(BillingCountry) %>%
  summarize(
    mean_invoice = mean(Total, na.rm = TRUE)
  )

invoice_country
OUTPUT RR OUTPUT
# A query:  ?? x 2
# Database: sqlite 3.53.3 [Chinook_Sqlite.sqlite]
   BillingCountry mean_invoice
   <chr>                 <dbl>
 1 Argentina              5.37
 2 Australia              5.37
 3 Austria                6.09
 4 Belgium                5.37
 5 Brazil                 5.43
 6 Canada                 5.43
 7 Chile                  6.66
 8 Czech Republic         6.45
 9 Denmark                5.37
10 Finland                5.95

Interpretasi: Interpretation: Rata-rata Total dihitung per BillingCountry. SQL AVG mengabaikan NULL.Mean Total is calculated by BillingCountry. SQL AVG ignores NULL.

Nilai mean_invoice merupakan rata-rata transaksi di setiap BillingCountry. Untuk menilai total pendapatan diperlukan SUM(Total), dan untuk menilai banyaknya transaksi diperlukan COUNT(*).mean_invoice is the average transaction value in each BillingCountry. To assess total revenue use SUM(Total), and to assess transaction frequency use COUNT(*).

dbplyr menerjemahkan sintaks dplyr menjadi SQL dan database melakukan komputasi. SQL AVG mengabaikan NULL; na.rm = TRUE menyatakan perilaku tersebut dengan eksplisit. Setelah collect(), hasil dapat dipakai untuk visualisasi.dbplyr translates dplyr syntax into SQL and the database performs computation. SQL AVG ignores NULL; na.rm = TRUE makes that behavior explicit. After collect(), results are ready for visualization.

SQL langsung versus dplyrDirect SQL versus dplyr

Untuk memahami hubungan SQL dan dbplyr, gunakan pertanyaan yang sama: siapa saja pelanggan yang berasal dari Brazil? Pada pendekatan pertama, tuliskan SELECT dan WHERE langsung. Pada pendekatan kedua, gunakan select() dan filter() terhadap lazy table; show_query() menunjukkan bagaimana sintaks tersebut diterjemahkan.To understand the relationship between SQL and dbplyr, use the same question: which customers are from Brazil? In the first approach, write SELECT and WHERE directly. In the second, use select() and filter() on a lazy table; show_query() shows how these commands are translated.

R
customer_brazil_sql <- dbGetQuery(
  chinook,
  "
  SELECT CustomerId, FirstName, LastName, Country
  FROM Customer
  WHERE Country = 'Brazil';
  "
)

customer_brazil_sql
OUTPUT RR OUTPUT
  CustomerId FirstName  LastName Country
1          1      Luís Gonçalves  Brazil
2         10   Eduardo   Martins  Brazil
3         11 Alexandre     Rocha  Brazil
4         12   Roberto   Almeida  Brazil
5         13  Fernanda     Ramos  Brazil

Interpretasi: Interpretation: Lima pelanggan Brazil ditampilkan.Five Brazilian customers are displayed.

Kesamaan isi tidak mensyaratkan urutan baris yang sama jika ORDER BY tidak ditetapkan. Untuk membandingkan dua hasil secara langsung, urutkan keduanya dengan CustomerId terlebih dahulu.Equal contents do not require identical row order if ORDER BY is unspecified. To compare the two results directly, sort both by CustomerId first.

Penggabungan data relasionalJoining relational data

Dalam database relasional, informasi yang diperlukan untuk menjawab satu pertanyaan dapat tersebar pada beberapa tabel. Sebagai contoh, nama pelanggan berada di Customer, sedangkan nilai transaksi berada di Invoice. Agar nama dan transaksi dapat dianalisis bersama, kita perlu menggabungkan kedua tabel menggunakan CustomerId.In a relational database, information needed to answer one question may be distributed across several tables. For example, customer names are in Customer, while transaction values are in Invoice. To analyze names and transactions together, we need to join these tables using CustomerId.

Pemilihan jenis join menentukan baris mana yang dipertahankan. Jika tujuan kita mempelajari semua pelanggan, termasuk yang belum mempunyai transaksi, left join merupakan pilihan yang sesuai. Jika hanya pelanggan dengan transaksi yang dibutuhkan, inner join dapat digunakan. Perbedaan ini penting karena jumlah baris setelah penggabungan dapat memengaruhi statistik yang dihitung.The type of join determines which rows are retained. If we want to study all customers, including those without transactions, a left join is appropriate. If only customers with transactions are needed, an inner join can be used. This distinction matters because the number of rows after joining can affect calculated statistics.

Informasi pelanggan berada pada Customer, sedangkan transaksi berada pada Invoice. Gabungkan berdasarkan CustomerId, bukan berdasarkan posisi baris. Satu pelanggan dapat memiliki banyak invoice, sehingga hasil join dapat menambah baris.Customer information lives in Customer, transactions in Invoice. Join by CustomerId, not by row position. A customer may have multiple invoices, so a join can increase the number of rows.

R
res <- tbl(
  chinook,
  "Customer"
) %>%
  select(
    CustomerId,
    FirstName,
    LastName,
    Country
  ) %>%
  left_join(
    y = tbl(
      chinook,
      "Invoice"
    ) %>%
      select(
        CustomerId,
        Total
      ),
    by = "CustomerId"
  )

glimpse(res)
OUTPUT RR OUTPUT
Rows: ??
Columns: 5
$ CustomerId <int> 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3,…
$ FirstName  <chr> "Luís", "Luís", "Luís", "Luís", "Luís", "Luís", "Luís", "Le…
$ LastName   <chr> "Gonçalves", "Gonçalves", "Gonçalves", "Gonçalves", "Gonçal…
$ Country    <chr> "Brazil", "Brazil", "Brazil", "Brazil", "Brazil", "Brazil",…
$ Total      <dbl> 3.98, 3.96, 5.94, 0.99, 1.98, 13.86, 8.91, 1.98, 13.86, 8.9…

Interpretasi: Interpretation: CustomerId muncul berulang karena seorang pelanggan dapat memiliki banyak invoice.CustomerId repeats because a customer may have multiple invoices.

CustomerId yang berulang merupakan konsekuensi relasi satu-ke-banyak. Jika tujuan akhirnya menghitung pelanggan, gunakan jumlah ID unik atau agregasikan invoice per pelanggan sebelum join.Repeated CustomerId values are a consequence of a one-to-many relationship. If the final goal is to count customers, use unique IDs or aggregate invoices per customer before joining.

Laboratorium join: data dplyrJoin laboratory: dplyr data

Sebelum menggabungkan tabel Chinook yang lebih besar, gunakan dua dataset kecil dari dplyr. band_members memuat nama dan band, sedangkan band_instruments memuat nama dan instrumen. Nama menjadi key untuk mencocokkan baris. Perhatikan bahwa tidak semua nama muncul pada kedua tabel; kondisi inilah yang membedakan hasil setiap join.Before joining larger Chinook tables, use two small datasets from dplyr. band_members contains names and bands, while band_instruments contains names and instruments. The name is the matching key. Not every name appears in both tables; this is what differentiates the results of each join.

R
data("band_members", package = "dplyr")
data("band_instruments", package = "dplyr")
data("band_instruments2", package = "dplyr")

band_members
band_instruments
band_instruments2
OUTPUT RR OUTPUT
# A tibble: 3 × 2
  name  band
  <chr> <chr>
1 Mick  Stones
2 John  Beatles
3 Paul  Beatles
# A tibble: 3 × 2
  name  plays
  <chr> <chr>
1 John  guitar
2 Paul  bass
3 Keith guitar
# A tibble: 3 × 2
  artist plays
  <chr>  <chr>
1 John   guitar
2 Paul   bass
3 Keith  guitar

Interpretasi: Interpretation: John dan Paul mempunyai pasangan; Mick dan Keith hanya ada pada salah satu tabel.John and Paul match; Mick and Keith appear in only one table.

Key yang cocok hanya John dan Paul. Mick tidak memiliki instrumen tercatat, sedangkan Keith tidak memiliki band tercatat pada tabel kiri.Only John and Paul have matching keys. Mick has no recorded instrument, while Keith has no recorded band in the left table.

Coba keenam jenis join pada skenario awal, kemudian pilih John dengan dua instrumen dan skenario tanpa pasangan. Bandingkan jumlah baris dan kolom hasil, terutama perbedaan antara mutating join dan filtering join.Try all six joins in the initial scenario, then select John with two instruments and the unmatched scenario. Compare the resulting row and column counts, especially mutating versus filtering joins.

INTERACTIVE 05 · JOIN LABORATORY

Pilih jenis join dan skenario keyChoose a join type and key scenario

inner_join()inner_join()

Gunakan inner_join() ketika informasi dari kedua tabel harus tersedia untuk sebuah key. Misalnya, kita ingin mengetahui band dan instrumen hanya untuk musisi yang tercatat pada kedua tabel. Nama yang tidak memiliki pasangan tidak ikut dalam hasil.Use inner_join() when a key must have information in both tables. For example, we want band and instrument information only for musicians listed in both tables. Names without a match are excluded.

Mempertahankan pasangan di kedua tabel.Keeps matched rows from both tables.

R
band_members %>%
  inner_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 2 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 John  Beatles guitar
2 Paul  Beatles bass

Interpretasi: Interpretation: Dua baris cocok: John dan Paul.Two matching rows: John and Paul.

Hasil lebih sedikit daripada tabel kiri karena Mick tidak memiliki pasangan. Pilihan ini sesuai jika hanya pasangan lengkap yang dibutuhkan.The result has fewer rows than the left table because Mick has no match. This is appropriate when only complete matches are needed.

left_join()left_join()

Jika semua anggota band adalah populasi yang ingin dipertahankan, jadikan band_members sebagai tabel kiri. left_join() menambahkan informasi instrumen apabila tersedia, tetapi tetap menyimpan anggota yang instrumennya belum tercatat.If all band members are the population to retain, make band_members the left table. left_join() adds instrument information when available, but keeps members whose instruments are not recorded.

Mempertahankan semua baris kiri; baris tanpa pasangan mendapat NA.Keeps all left rows; unmatched right fields become NA.

R
band_members %>%
  left_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 3 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 Mick  Stones  <NA>
2 John  Beatles guitar
3 Paul  Beatles bass

Interpretasi: Interpretation: Tiga anggota band dipertahankan; Mick mempunyai NA pada plays.All three band members remain; Mick has NA for plays.

NA pada plays menunjukkan tidak ada pasangan instrumen, bukan bahwa Mick pasti tidak memainkan instrumen.NA in plays indicates no matching instrument record, not that Mick necessarily plays no instrument.

right_join()right_join()

right_join() menggunakan tabel kanan sebagai acuan. Jika kita ingin mempertahankan semua pemain instrumen, termasuk pemain yang belum diketahui band-nya, band_instruments harus menjadi tabel kanan.right_join() uses the right table as the reference. If we want to retain every instrument player, including those without known band information, band_instruments should be the right table.

Mempertahankan semua baris kanan.Keeps all right rows.

R
band_members %>%
  right_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 3 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 John  Beatles guitar
2 Paul  Beatles bass
3 Keith <NA>    guitar

Interpretasi: Interpretation: Tiga pemain instrumen dipertahankan; Keith mempunyai NA pada band.All three instrument players remain; Keith has NA for band.

Keith tetap muncul karena tabel kanan adalah acuan. Informasi band yang tidak ditemukan ditandai NA.Keith remains because the right table is the reference. Missing band information is marked NA.

full_join()full_join()

Untuk memperoleh gabungan seluruh nama dari kedua tabel, gunakan full_join(). Informasi yang tersedia pada kedua tabel dipasangkan, sedangkan nama yang hanya muncul pada salah satu tabel tetap ditampilkan dengan NA pada atribut yang tidak tersedia.To obtain the union of names across both tables, use full_join(). Available information is matched, while names found in only one table remain with NA in unavailable attributes.

Mempertahankan seluruh baris dari kedua tabel.Keeps all rows from both tables.

R
band_members %>%
  full_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 4 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 Mick  Stones  <NA>
2 John  Beatles guitar
3 Paul  Beatles bass
4 Keith <NA>    guitar

Interpretasi: Interpretation: Empat nama dipertahankan dari kedua tabel.Four names are retained from both tables.

Full join mempertahankan cakupan kedua tabel, tetapi menghasilkan atribut yang hilang untuk nama yang tidak mempunyai pasangan.A full join retains the coverage of both tables, but creates missing attributes for unmatched names.

semi_join()semi_join()

Berbeda dari mutating join, semi_join() tidak menambahkan atribut dari tabel kanan. Fungsi ini berguna ketika kita hanya perlu memilih anggota band yang mempunyai catatan instrumen, tanpa perlu mengetahui jenis instrumennya pada hasil.Unlike mutating joins, semi_join() does not append attributes from the right table. It is useful when we only need to select band members with an instrument record, without including the instrument itself in the result.

Memilih baris kiri yang punya pasangan tanpa menambah kolom kanan.Filters left rows with a match without adding right columns.

R
band_members %>%
  semi_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 2 × 2
  name  band
  <chr> <chr>
1 John  Beatles
2 Paul  Beatles

Interpretasi: Interpretation: John dan Paul tetap ada, tanpa kolom plays.John and Paul remain, without the plays column.

Jumlah kolom sama seperti tabel kiri. Satu nama di tabel kiri tidak diperbanyak oleh banyaknya pasangan pada tabel kanan.The number of columns is unchanged from the left table. A left-side name is not duplicated by multiple matches on the right.

anti_join()anti_join()

anti_join() merupakan kebalikan pemeriksaan keberadaan pasangan. Gunakan untuk mencari anggota band yang belum mempunyai catatan instrumen. Dalam pengolahan data nyata, pola ini juga bermanfaat untuk audit key yang tidak ditemukan pada tabel referensi.anti_join() reverses the match-existence check. Use it to find band members with no instrument record. In real data processing, this pattern also helps audit keys missing from a reference table.

Memilih baris kiri tanpa pasangan.Filters left rows without a match.

R
band_members %>%
  anti_join(
    band_instruments,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 1 × 2
  name  band
  <chr> <chr>
1 Mick  Stones

Interpretasi: Interpretation: Mick tidak mempunyai pasangan.Mick has no match.

Hasil ini merupakan daftar key yang perlu diperiksa lebih lanjut, bukan bukti bahwa atribut tersebut tidak ada di dunia nyata.This result identifies keys requiring further inspection, rather than proving that the attribute does not exist in reality.

Key berulang dan tidak memiliki pasanganRepeated and unmatched keys

Join tidak selalu memasangkan satu baris dengan satu baris. Jika John memiliki dua instrumen, satu baris John pada band_members dapat menghasilkan dua baris pada hasil. Jika tidak ada key yang cocok, jenis join menentukan apakah baris dipertahankan. Selain itu, kolom key dapat memiliki nama yang berbeda sehingga hubungan harus dituliskan secara eksplisit.A join does not always match one row to one row. If John has two instruments, one John row in band_members can produce two result rows. If no keys match, the join type determines whether rows are retained. Key columns may also have different names, requiring explicit mapping.

R
band_instruments_edit <- band_instruments %>%
  bind_rows(
    data.frame(
      name = "John",
      plays = "harmonica"
    )
  )

band_instruments_edit
OUTPUT RR OUTPUT
# A tibble: 4 × 2
  name  plays
  <chr> <chr>
1 John  guitar
2 Paul  bass
3 Keith guitar
4 John  harmonica
R
band_members %>%
  left_join(
    band_instruments_edit,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 4 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 Mick  Stones  <NA>
2 John  Beatles guitar
3 John  Beatles harmonica
4 Paul  Beatles bass
R
band_members %>%
  right_join(
    band_instruments_edit,
    by = "name"
  )
OUTPUT RR OUTPUT
# A tibble: 4 × 3
  name  band    plays
  <chr> <chr>   <chr>
1 John  Beatles guitar
2 John  Beatles harmonica
3 Paul  Beatles bass
4 Keith <NA>    guitar

Interpretasi: Interpretation: John memiliki dua pasangan, sehingga satu baris kiri menghasilkan dua baris.John has two matches, so one left row produces two result rows.

Periksa relasi satu-ke-satu, satu-ke-banyak, atau banyak-ke-banyak sebelum menghitung ringkasan. Pengulangan akibat join tidak boleh langsung dihapus tanpa memahami unit observasi.Check whether the relationship is one-to-one, one-to-many or many-to-many before calculating summaries. Repetitions introduced by a join should not be removed without understanding the observational unit.

Jika satu key muncul beberapa kali pada tabel kanan, baris kiri yang cocok muncul beberapa kali. Periksa jumlah baris dan keunikan key sebelum serta sesudah join. Jika nama key berbeda, tuliskan pasangan nama pada by.If a key occurs multiple times in the right table, a matching left row occurs multiple times. Check row counts and key uniqueness before and after joining. If key names differ, map them in by.

Visualisasi dan interpretasi hasilVisualization and interpretation

SQL membantu menyiapkan informasi yang diperlukan, tetapi tabel hasil query belum tentu merupakan bentuk penyajian yang paling mudah dipahami. Setelah data diambil ke R, ggplot2 digunakan untuk membandingkan kelompok melalui diagram batang dan memeriksa hubungan dua variabel numerik melalui scatter plot.SQL helps prepare the required information, but a query result table is not always the easiest representation to interpret. After retrieving data into R, ggplot2 is used to compare groups with bar charts and inspect relationships between numerical variables with scatter plots.

Jenis grafik mengikuti unit observasi hasil query. Untuk perbandingan antaralbum, gunakan ringkasan satu baris per album. Untuk hubungan durasi dan ukuran file, pertahankan satu baris per track. Dengan demikian, visualisasi menjawab pertanyaan yang tepat dan tidak mencampur unit analisis.The chart type follows the observational unit of the query result. For comparisons across albums, use one summary row per album. For the relationship between duration and file size, retain one row per track. This ensures the visualization answers the intended question without mixing units of analysis.

Jumlah track setiap albumTrack count for every album

Gunakan album_summary yang diperoleh dari GROUP BY. Karena N sudah berisi jumlah track, geom_col() menggambar tinggi batang sesuai nilai N tanpa menghitung baris lagi. Saat seluruh album ditampilkan, banyaknya kategori membuat label sulit dibaca; pilih 20 album dengan N tertinggi untuk perbandingan yang lebih terfokus.Use album_summary obtained from GROUP BY. Because N already contains track counts, geom_col() draws bar heights according to N without counting rows again. With every album displayed, numerous categories crowd the labels; select the 20 albums with the highest N for a more focused comparison.

R
ggplot(
  data = album_summary,
  aes(
    x = as.factor(AlbumId),
    y = N
  )
) +
  geom_col() +
  labs(
    title = "Number of Tracks in Each Album",
    x = "Album ID",
    y = "Number of Tracks"
  ) +
  theme_minimal()
All 347 album groups; labels are difficult to read
Seluruh 347 kelompok album; label sulit dibacaAll 347 album groups; labels are difficult to read

Interpretasi: Interpretation: Banyak kategori membuat label sulit dibaca.Many categories make labels difficult to read.

Batang mewakili satu album, bukan satu track. Jika beberapa album memiliki N sama pada batas Top 20, pilihan album yang ditampilkan dapat bergantung pada aturan tie-breaking.Each bar represents an album, not a track. If albums have equal N at the Top 20 boundary, the displayed selection may depend on tie-breaking.

Geser nilai Top untuk memusatkan perhatian pada album teratas. Visualisasi ini membantu menentukan cakupan tampilan; grafik ggplot2 pada tab sebelumnya tetap menampilkan hasil analisis R.Move the Top slider to focus on leading albums. This visualization helps choose the display scope; the ggplot2 plot in the preceding tab remains the R analysis result.

INTERACTIVE 06 · TOP N

Pilih jumlah album yang ditampilkanChoose the number of albums displayed

Simulasi menggunakan 20 album dengan jumlah track terbesar. Geser pengatur untuk memilih jumlah album yang ditampilkan.This simulation uses the 20 albums with the highest track counts. Move the slider to choose how many albums to show.

Album 141 memiliki 57 track, jauh lebih banyak daripada album 23 (34 track). Ini menunjukkan jumlah track, bukan popularitas atau penjualan album. reorder() mengurutkan kategori dan coord_flip() mempermudah pembacaan.Album 141 has 57 tracks, considerably more than album 23 (34). This shows track counts, not popularity or album sales. reorder() sorts categories and coord_flip() improves readability.

Rata-rata invoice menurut negara penagihanMean invoice by billing country

Gunakan invoice_country_df dari agregasi sebelumnya. Pada diagram batang, panjang batang menyatakan rata-rata nilai transaksi per negara penagihan. Urutkan kategori berdasarkan mean_invoice dan gunakan coord_flip() agar nama negara dapat dibaca dengan nyaman.Use invoice_country_df from the earlier aggregation. Bar length represents the average transaction value per billing country. Order categories by mean_invoice and use coord_flip() to make country names easier to read.

R
ggplot(
  data = invoice_country_df,
  aes(
    x = reorder(BillingCountry, mean_invoice),
    y = mean_invoice
  )
) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Average Invoice Value by Country",
    x = "Country",
    y = "Average Invoice Value"
  ) +
  theme_minimal()
Average invoice by country
Rata-rata invoice berdasarkan negaraAverage invoice by country

Interpretasi: Interpretation: Chile mempunyai rata-rata invoice tertinggi pada hasil query, 6,66; ini bukan total pendapatan.Chile has the highest mean invoice in the query result, 6.66; this is not total revenue.

Perbedaan rata-rata perlu dibaca bersama banyaknya invoice per negara. Rata-rata tertinggi tidak berarti suatu negara menyumbang pendapatan terbesar.Differences in averages should be read alongside invoice counts per country. The highest average does not imply the highest contribution to revenue.

Lihat tabel hasil lengkap (24 negara)View full results (24 countries)
BillingCountrymean_invoice
Argentina5.374286
Australia5.374286
Austria6.088571
Belgium5.374286
Brazil5.431429
Canada5.427857
Chile6.660000
Czech Republic6.445714
Denmark5.374286
Finland5.945714
France5.574286
Germany5.588571
Hungary6.517143
India5.789231
Ireland6.517143
Italy5.374286
Netherlands5.802857
Norway5.660000
Poland5.374286
Portugal5.517143
Spain5.374286
Sweden5.517143
USA5.747912
United Kingdom5.374286

Chile memiliki rata-rata invoice tertinggi pada hasil query (6,66). Rata-rata invoice bukan total pendapatan; pertimbangkan jumlah transaksi sebelum membandingkan negara.Chile has the highest mean invoice in the query result (6.66). Mean invoice is not total revenue; consider transaction counts before comparing countries.

Jumlah customer per negaraCustomers per country

Untuk mengetahui distribusi pelanggan, gunakan tabel Customer, bukan Invoice. Jika kita menghitung baris Invoice, pelanggan yang bertransaksi berkali-kali dapat terhitung berulang. group_by(Country) dan n() menghasilkan jumlah pelanggan per negara sebelum data dipindahkan ke R untuk visualisasi.To inspect customer distribution, use Customer rather than Invoice. Counting Invoice rows would count customers with multiple transactions repeatedly. group_by(Country) and n() produce customer counts by country before data are transferred to R for visualization.

R
customer_country <- tbl(
  chinook,
  "Customer"
) %>%
  group_by(Country) %>%
  summarize(
    n_customer = n()
  ) %>%
  as.data.frame()

customer_country
OUTPUT RR OUTPUT
          Country n_customer
1       Argentina          1
2       Australia          1
3         Austria          1
4         Belgium          1
5          Brazil          5
6          Canada          8
7           Chile          1
8  Czech Republic          2
9         Denmark          1
10        Finland          1
11         France          5
12        Germany          4
13        Hungary          1
14          India          2
15        Ireland          1
16          Italy          1
17    Netherlands          1
18         Norway          1
19         Poland          1
20       Portugal          2
21          Spain          1
22         Sweden          1
23            USA         13
24 United Kingdom          3
R
ggplot(
  data = customer_country,
  aes(
    x = reorder(Country, n_customer),
    y = n_customer
  )
) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Number of Customers by Country",
    x = "Country",
    y = "Number of Customers"
  ) +
  theme_minimal()
Customer count by country
Jumlah customer berdasarkan negaraCustomer count by country

Interpretasi: Interpretation: USA 13, Kanada 8, Brazil dan Prancis 5 pelanggan masing-masing. Ini distribusi dalam database contoh.USA 13, Canada 8, Brazil and France 5 customers each. This is the distribution in the sample database.

Diagram menghitung baris pada tabel Customer, sehingga satu pelanggan dihitung sekali. Distribusi ini hanya menggambarkan pelanggan yang tercatat pada Chinook.The chart counts Customer rows, so each customer is counted once. The distribution describes only customers recorded in Chinook.

Lihat tabel hasil lengkap (24 negara)View full results (24 countries)
Countryn_customer
Argentina1
Australia1
Austria1
Belgium1
Brazil5
Canada8
Chile1
Czech Republic2
Denmark1
Finland1
France5
Germany4
Hungary1
India2
Ireland1
Italy1
Netherlands1
Norway1
Poland1
Portugal2
Spain1
Sweden1
USA13
United Kingdom3

USA memiliki 13 pelanggan, Kanada 8, Brazil dan Prancis masing-masing 5. Ini merupakan distribusi 59 pelanggan pada database contoh, bukan gambaran pasar global.The USA has 13 customers, Canada 8, Brazil and France 5 each. This is the distribution of 59 customers in the sample database, not a representation of the global market.

Durasi track dan ukuran fileTrack duration and file size

Durasi dan ukuran file adalah dua variabel numerik yang dapat dipelajari bersama tanpa agregasi. Gunakan WHERE untuk memastikan keduanya tidak NULL, kemudian letakkan Milliseconds pada sumbu horizontal dan Bytes pada sumbu vertikal. geom_point() menampilkan satu titik per track, dengan transparansi agar titik yang bertumpuk lebih mudah terlihat.Duration and file size are two numerical variables that can be studied together without aggregation. Use WHERE to ensure neither is NULL, then place Milliseconds on the horizontal axis and Bytes on the vertical axis. geom_point() shows one point per track, with transparency to help reveal overlapping points.

R
track_plot <- dbGetQuery(
  chinook,
  "
  SELECT TrackId,
         Name,
         Milliseconds,
         Bytes,
         UnitPrice
  FROM Track
  WHERE Milliseconds IS NOT NULL
    AND Bytes IS NOT NULL;
  "
)

head(track_plot)
OUTPUT RR OUTPUT
  TrackId                                    Name Milliseconds    Bytes
1       1 For Those About To Rock (We Salute You)       343719 11170334
2       2                       Balls to the Wall       342562  5510424
3       3                         Fast As a Shark       230619  3990994
4       4                       Restless and Wild       252051  4331779
5       5                    Princess of the Dawn       375418  6290521
6       6                   Put The Finger On You       205662  6713451
  UnitPrice
1      0.99
2      0.99
3      0.99
4      0.99
5      0.99
6      0.99
R
ggplot(
  data = track_plot,
  aes(
    x = Milliseconds,
    y = Bytes
  )
) +
  geom_point(alpha = 0.4) +
  labs(
    title = "Relationship Between Track Duration and File Size",
    x = "Duration (Milliseconds)",
    y = "File Size (Bytes)"
  ) +
  theme_minimal()
Duration versus file size in the original output
Hubungan durasi dan ukuran file Duration versus file size

Interpretasi: Interpretation: Setiap titik mewakili satu track. Durasi lebih panjang cenderung berkaitan dengan ukuran lebih besar; jenis media juga dapat berpengaruh.Each point is one track. Longer duration tends to correspond to larger files; media type may also matter.

Pola titik merupakan hubungan deskriptif. Untuk menjelaskan perbedaan ukuran file pada durasi yang sama, periksa karakteristik media atau encoding; grafik saja tidak membuktikan sebab-akibat.The point pattern is descriptive. To explain file-size differences at equal durations, inspect media characteristics or encoding; the plot alone does not establish causality.

Setiap titik adalah satu track. Grafik menunjukkan pola peningkatan ukuran file seiring durasi, tetapi ada kelompok titik yang berbeda; tipe media atau encoding mungkin berperan. Plot ini bersifat deskriptif dan tidak membuktikan sebab-akibat.Each point is one track. The chart shows a tendency for file size to increase with duration, with distinct clusters; media type or encoding may play a role. The plot is descriptive and does not establish causality.

Menutup koneksiClosing the connection

Setelah data yang diperlukan diambil dan grafik dibuat, koneksi SQLite tidak perlu terus dibiarkan terbuka. dbDisconnect() melepaskan koneksi, sedangkan data.frame yang telah diambil masih tersedia di R. Lazy table yang belum diambil memerlukan koneksi aktif jika akan dieksekusi.After retrieving the required data and creating plots, the SQLite connection does not need to remain open. dbDisconnect() releases the connection, while previously retrieved data.frames remain available in R. A lazy table that has not been retrieved requires an active connection for execution.

SQLite
→
dbConnect()
→
dbGetQuery()
tbl() → collect()
→
ggplot2
R
dbDisconnect(chinook)

dbIsValid(chinook)
OUTPUT RR OUTPUT
[1] FALSE
R
stopifnot(file.exists(db_path))
chinook <- dbConnect(
  RSQLite::SQLite(),
  db_path,
  flags = RSQLite::SQLITE_RO
)

Interpretasi: Interpretation: FALSE menunjukkan koneksi telah ditutup. Hubungkan kembali bila diperlukan.FALSE means the connection is closed. Reconnect if needed.

Jika masih ingin mengirim query, buat koneksi lagi. Data lokal yang sudah diambil tidak perlu dibaca ulang hanya untuk membuat grafik.If more queries are needed, reconnect. Local data already retrieved do not need to be read again just to create a plot.

Query yang memerlukan koneksi tidak dapat dijalankan setelah koneksi ditutup. Untuk kembali menggunakan database, buat koneksi ulang.Queries requiring the connection cannot run once it is closed. Reconnect to use the database again.

Latihan mandiriIndependent exercise

Sekarang terapkan alur yang telah dipelajari pada database lain. Berbeda dari Chinook, Mental Health Database menyimpan data survei: pertanyaan dan jawaban berada pada tabel terpisah. Untuk menghitung responden menurut gender atau negara, kita harus terlebih dahulu mengenali pertanyaan yang sesuai dan memahami hubungan antartabel.Now apply the workflow to a different database. Unlike Chinook, the Mental Health Database stores survey data: questions and answers are in separate tables. To count respondents by gender or country, we first need to identify the relevant question and understand the relationships between tables.

Buka database, periksa struktur Survey, Question, dan Answer, kemudian susun query secara bertahap. Lihat beberapa jawaban sebelum melakukan agregasi; periksa apakah satu responden dapat memiliki lebih dari satu baris untuk pertanyaan yang sama. Laporkan hasil beserta unit analisisnya.Open the database, inspect Survey, Question and Answer, then construct the query step by step. Inspect several answers before aggregation; check whether a respondent can have more than one row for the same question. Report the results with their unit of analysis.

Dataset Open Source Mental Illness (OSMI) berasal dari survei 2014, 2016, 2017, 2018, dan 2019 mengenai sikap terhadap kesehatan mental serta frekuensi gangguan kesehatan mental di lingkungan kerja teknologi. Data mentah diproses melalui Python, SQL, dan Excel: pertanyaan yang serupa dikelompokkan, nilai jawaban diseragamkan (misalnya 1 dan 1.0), dan kesalahan ejaan diperbaiki.The Open Source Mental Illness (OSMI) dataset comes from surveys in 2014, 2016, 2017, 2018 and 2019 about attitudes towards mental health and the frequency of mental health disorders in the technology workplace. Raw data were cleaned using Python, SQL and Excel: similar questions were grouped, answer formats standardized (e.g., 1 and 1.0), and spelling errors corrected.

TableFields
SurveySurveyID (PK), Description
QuestionQuestionID (PK), QuestionText
AnswerSurveyID (FK), UserID, QuestionID (FK), AnswerText

SurveyID menunjukkan tahun. Pertanyaan dapat dipakai pada beberapa survei. Answer menghubungkan survei, responden, dan pertanyaan; sebagian pertanyaan mengizinkan lebih dari satu jawaban. Karena itu, periksa keunikan gabungan key dan unit analisis sebelum menggunakan COUNT(*).SurveyID denotes the year. Questions may be reused across surveys. Answer links surveys, respondents and questions; some questions allow multiple answers. Check composite key uniqueness and the unit of analysis before using COUNT(*).

Pertanyaan 1Question 1

Tampilkan kategori gender responden survei. Gender mana yang memiliki jumlah responden paling sedikit?Show the gender categories of survey respondents. Which gender has the smallest number of respondents?

PetunjukHint

Gunakan COUNT(*) AS N. Identifikasi QuestionID yang relevan dan pastikan baris yang dihitung sesuai unit responden.Use COUNT(*) AS N. Identify the relevant QuestionID and ensure the rows counted correspond to respondents.

Pertanyaan 2Question 2

Tampilkan negara asal responden survei. Urutkan negara berdasarkan jumlah responden terbesar.Show the countries of origin of survey respondents. Sort countries by the largest number of respondents.

PetunjukHint

Gunakan COUNT(*) AS N. Identifikasi QuestionID yang relevan dan pastikan baris yang dihitung sesuai unit responden.Use COUNT(*) AS N. Identify the relevant QuestionID and ensure the rows counted correspond to respondents.

Kerjakan query dalam DB Browser, kemudian jalankan dari RStudio menggunakan dbGetQuery() pada koneksi database latihan. Tuliskan interpretasi dari hasil yang kamu peroleh.Run queries in DB Browser, then execute them in RStudio with dbGetQuery() using a connection to the exercise database. Write an interpretation of your results.

RingkasanSummary

Praktikum ini memperlihatkan bagaimana data relasional dapat diolah menjadi informasi yang siap dianalisis. SELECT memilih variabel, WHERE menentukan observasi yang relevan, dan GROUP BY mengubah unit observasi menjadi ringkasan kelompok. ORDER BY membantu membaca hasil, sedangkan join menggabungkan informasi berdasarkan key.This practicum demonstrates how relational data can be transformed into information ready for analysis. SELECT chooses variables, WHERE identifies relevant observations, and GROUP BY transforms the observational unit into group summaries. ORDER BY makes results easier to inspect, while joins combine information using keys.

Di RStudio, dbGetQuery() mengambil hasil SQL langsung sebagai data.frame. Sebaliknya, tbl() bersama dbplyr memungkinkan kita menyusun operasi sebelum mengambil hasil dengan collect(). Strategi kedua membantu membatasi perpindahan data ketika hanya ringkasan tertentu yang dibutuhkan.In RStudio, dbGetQuery() retrieves SQL results directly as a data.frame. In contrast, tbl() together with dbplyr allows operations to be constructed before retrieving results with collect(). The latter strategy helps limit data transfer when only a particular summary is needed.

Sebelum membuat visualisasi atau model, selalu periksa jumlah baris, kolom, nilai hilang, dan key. Hasil join dapat mengandung pengulangan yang sah, tetapi penghitungan pada unit yang salah dapat memberikan kesimpulan yang keliru. Setelah pengolahan selesai, tutup koneksi database.Before creating visualizations or models, always check row counts, columns, missing values and keys. Joined results may contain legitimate repetitions, but counting at the wrong observational unit can produce misleading conclusions. Close the database connection when processing is complete.

SQL / RFungsiPurpose
SELECT / select()Memilih kolomChoose columns
WHERE / filter()Menyaring barisFilter rows
ORDER BY / arrange()MengurutkanSort
DISTINCT / distinct()Nilai unikUnique values
LIMIT / head()Membatasi hasilLimit results
BETWEEN / IN / IS NULLKondisi seleksiSelection conditions
GROUP BY / group_by()MengelompokkanGroup
COUNT / SUM / AVG / MIN / MAXAgregasiAggregation
HAVINGMenyaring kelompokFilter groups
CREATE TABLE ASMenyimpan query sebagai tabelSave query as a table
dbConnect() / dbIsValid() / dbListTables()Koneksi dan validasiConnect and validate
dbGetQuery() / dbExecute()Query / perubahan databaseQuery / database changes
tbl() / show_query()Lazy table dan SQL terjemahanLazy table and translated SQL
collect() / as.data.frame()Mengambil hasil ke RRetrieve results into R
inner / left / right / full_join()Menggabungkan kolom sesuai pasanganCombine columns according to matches
semi_join() / anti_join()Menyaring berdasarkan pasanganFilter by matches
ggplot()Visualisasi hasilVisualize results
dbDisconnect()Menutup koneksiClose connection

Inti praktikum: tentukan pertanyaan, pilih tabel dan unit observasi, susun query, periksa hasil, ambil data secukupnya ke R, dan interpretasikan visualisasi.The practical workflow: define a question, choose the table and observational unit, construct a query, inspect results, retrieve only the needed data into R, and interpret visualizations.

Dokumentasi pendukungSupporting documentation

SQLite SQL language · DBI · RSQLite · dbplyr · dplyr · ggplot2

PENULISAUTHOR
Unique Desyrre A. Resiloy