Connection to a Database

Contoh pemanggilan database pada publikasi ini yaitu menggunakan contoh data chinook. Untuk dapat melakukannya, diperlukan beberapa package yaitu DBI dan RSQLite.

install.packages(c("RSQLite", "DBI"), dependencies = TRUE)

Selanjutnya kita panggil package tidyverse yang sudah mencakup package dplry dan dbplyr. Selain itu, jangan lupa untuk memanggil package RSQLite dan DBI.

library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.1.2
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.5     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.0.2     v forcats 0.5.1
## Warning: package 'ggplot2' was built under R version 4.1.2
## Warning: package 'stringr' was built under R version 4.1.2
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(RSQLite)
## Warning: package 'RSQLite' was built under R version 4.1.2
library(DBI)
## Warning: package 'DBI' was built under R version 4.1.2

Secara umum, koneksi terhadap database pada R software adalah dengan menggunakan syntax berikut:

DBI::dbConnect(RSQLite::SQLite(), path = ":dbname:")
## <SQLiteConnection>
##   Path: 
##   Extensions: TRUE

Fungsi juga dapat dijalankankan tanpa memanggil package dengan perintah library() atau require(), jika syntax yang ditulis menyertakan nama package tempat fungsi tersebut berasal. Penyertaan ini dengan menggunakan tanda ::.

A. Akses Database

1. Engine SQL

chinook<-DBI::dbConnect(RSQLite::SQLite(), "C:/sqlite/chinook.db")
RSQLite::dbListTables(chinook)
##  [1] "albums"          "artists"         "customers"       "employees"      
##  [5] "genres"          "invoice_items"   "invoices"        "media_types"    
##  [9] "playlist_track"  "playlists"       "sqlite_sequence" "sqlite_stat1"   
## [13] "tracks"

Object chinook ini akan digunakan pada opsi connection, kemudian pada opsi engine digunakan "sql". Sehingga didalamnya kita bisa menulis syntax SQL.

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

2. Menggunakan DPLYR

chinook<-DBI::dbConnect(RSQLite::SQLite(), "C:/sqlite/chinook.db")
class(chinook)
## [1] "SQLiteConnection"
## attr(,"package")
## [1] "RSQLite"
RSQLite::dbListTables(chinook)
##  [1] "albums"          "artists"         "customers"       "employees"      
##  [5] "genres"          "invoice_items"   "invoices"        "media_types"    
##  [9] "playlist_track"  "playlists"       "sqlite_sequence" "sqlite_stat1"   
## [13] "tracks"
tracks<-dplyr::tbl(chinook,"Tracks")
class(tracks)
## [1] "tbl_SQLiteConnection" "tbl_dbi"              "tbl_sql"             
## [4] "tbl_lazy"             "tbl"

tracks merupakan object dengan class tbl yang dapat diperlakukan mirip seperti data.frame. Berikut adalah isi dari obyek chinook

tracks
## # Source:   table<Tracks> [?? x 9]
## # Database: sqlite 3.37.0 [C:\sqlite\chinook.db]
##    TrackId Name     AlbumId MediaTypeId GenreId Composer     Milliseconds  Bytes
##      <int> <chr>      <int>       <int>   <int> <chr>               <int>  <int>
##  1       1 For Tho~       1           1       1 Angus Young~       343719 1.12e7
##  2       2 Balls t~       2           2       1 <NA>               342562 5.51e6
##  3       3 Fast As~       3           2       1 F. Baltes, ~       230619 3.99e6
##  4       4 Restles~       3           2       1 F. Baltes, ~       252051 4.33e6
##  5       5 Princes~       3           2       1 Deaffy & R.~       375418 6.29e6
##  6       6 Put The~       1           1       1 Angus Young~       205662 6.71e6
##  7       7 Let's G~       1           1       1 Angus Young~       233926 7.64e6
##  8       8 Inject ~       1           1       1 Angus Young~       210834 6.85e6
##  9       9 Snowbal~       1           1       1 Angus Young~       203102 6.60e6
## 10      10 Evil Wa~       1           1       1 Angus Young~       263497 8.61e6
## # ... with more rows, and 1 more variable: UnitPrice <dbl>
q <- tracks%>% select(-TrackId, -Name, -AlbumId, -Composer)
q
## # Source:   lazy query [?? x 5]
## # Database: sqlite 3.37.0 [C:\sqlite\chinook.db]
##    MediaTypeId GenreId Milliseconds    Bytes UnitPrice
##          <int>   <int>        <int>    <int>     <dbl>
##  1           1       1       343719 11170334      0.99
##  2           2       1       342562  5510424      0.99
##  3           2       1       230619  3990994      0.99
##  4           2       1       252051  4331779      0.99
##  5           2       1       375418  6290521      0.99
##  6           1       1       205662  6713451      0.99
##  7           1       1       233926  7636561      0.99
##  8           1       1       210834  6852860      0.99
##  9           1       1       203102  6599424      0.99
## 10           1       1       263497  8611245      0.99
## # ... with more rows
dplyr::show_query(q)
## <SQL>
## SELECT `MediaTypeId`, `GenreId`, `Milliseconds`, `Bytes`, `UnitPrice`
## FROM `Tracks`

B. Data Wrangling

Dataset yang digunakan adalah cars yang tersedia pada package default R datasets.

library(datasets)
data("cars")
cars <- tibble::as.tibble(cars)
## Warning: `as.tibble()` was deprecated in tibble 2.0.0.
## Please use `as_tibble()` instead.
## The signature and semantics have changed, see `?as_tibble`.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.

Untuk mengetahui informasi terkait dataset dapat menggunakan syntax ? sebelum nama dataset.

?cars
## starting httpd help server ... done
View(cars)

tidyverse merupakan kumpulan dari beberapa package, salah satunya adalah package dplyr. Berikut adalah beberapa contoh penggunaan package dplyr.

1. Fungsi Summarise()

Fungsi ini digunakan untuk meringkas data

cars %>% group_by(speed)%>%summarise(mean=mean(dist))
## # A tibble: 19 x 2
##    speed  mean
##    <dbl> <dbl>
##  1     4   6  
##  2     7  13  
##  3     8  16  
##  4     9  10  
##  5    10  26  
##  6    11  22.5
##  7    12  21.5
##  8    13  35  
##  9    14  50.5
## 10    15  33.3
## 11    16  36  
## 12    17  40.7
## 13    18  64.5
## 14    19  50  
## 15    20  50.4
## 16    22  66  
## 17    23  54  
## 18    24  93.8
## 19    25  85

2. Fungsi Arrange()

Fungsi ini digunakan untuk mengurutkan data berdasarkan suatu peubah

cars %>% arrange(desc(dist))
## # A tibble: 50 x 2
##    speed  dist
##    <dbl> <dbl>
##  1    24   120
##  2    24    93
##  3    24    92
##  4    25    85
##  5    18    84
##  6    14    80
##  7    18    76
##  8    24    70
##  9    19    68
## 10    22    66
## # ... with 40 more rows

3. Fungsi Filter()

Fungsi ini digunakan untuk memilih sebagian data berdasarkan nilai tertentu

cars %>% filter(speed>20)
## # A tibble: 7 x 2
##   speed  dist
##   <dbl> <dbl>
## 1    22    66
## 2    23    54
## 3    24    70
## 4    24    92
## 5    24    93
## 6    24   120
## 7    25    85

4. Fungsi Select()

Fungsi ini digunakan untuk memilih subset data berdasarkan peubah tertentu

cars %>% select(speed, dist)
## # A tibble: 50 x 2
##    speed  dist
##    <dbl> <dbl>
##  1     4     2
##  2     4    10
##  3     7     4
##  4     7    22
##  5     8    16
##  6     9    10
##  7    10    18
##  8    10    26
##  9    10    34
## 10    11    17
## # ... with 40 more rows

5. Fungsi Mutate()

Fungsi ini digunakan untuk menambahkan peubah baru pada data

cars %>% mutate(time=dist/speed)
## # A tibble: 50 x 3
##    speed  dist  time
##    <dbl> <dbl> <dbl>
##  1     4     2 0.5  
##  2     4    10 2.5  
##  3     7     4 0.571
##  4     7    22 3.14 
##  5     8    16 2    
##  6     9    10 1.11 
##  7    10    18 1.8  
##  8    10    26 2.6  
##  9    10    34 3.4  
## 10    11    17 1.55 
## # ... with 40 more rows