Pada bagian ini saya belajar tentang pipes with magrittr.

note : sedang malas nyusun kata-kata dan ngetik jadi copas

library(tidyverse)
library(magrittr)

The point of the pipe (%>%) is to help you write code in a way that is easier to read and understand.

Let’s take a look at an actual data manipulation pipeline where we add a new column to ggplot2::diamonds:

diamonds <- ggplot2::diamonds # mengambil dataset diamond pada package ggplot2
diamonds
## # A tibble: 53,940 x 10
##    carat cut       color clarity depth table price     x     y     z
##    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
##  1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
##  2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
##  3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
##  4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
##  5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75
##  6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
##  7 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
##  8 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
##  9 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49
## 10 0.23  Very Good H     VS1      59.4    61   338  4     4.05  2.39
## # ... with 53,930 more rows
diamonds2 <- diamonds %>%
  dplyr::mutate(price_per_carat = price / carat) # melakukan mutate pada package dplyr 
diamonds2
## # A tibble: 53,940 x 11
##    carat cut   color clarity depth table price     x     y     z price_per_carat
##    <dbl> <ord> <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>           <dbl>
##  1 0.23  Ideal E     SI2      61.5    55   326  3.95  3.98  2.43           1417.
##  2 0.21  Prem~ E     SI1      59.8    61   326  3.89  3.84  2.31           1552.
##  3 0.23  Good  E     VS1      56.9    65   327  4.05  4.07  2.31           1422.
##  4 0.290 Prem~ I     VS2      62.4    58   334  4.2   4.23  2.63           1152.
##  5 0.31  Good  J     SI2      63.3    58   335  4.34  4.35  2.75           1081.
##  6 0.24  Very~ J     VVS2     62.8    57   336  3.94  3.96  2.48           1400 
##  7 0.24  Very~ I     VVS1     62.3    57   336  3.95  3.98  2.47           1400 
##  8 0.26  Very~ H     SI1      61.9    55   337  4.07  4.11  2.53           1296.
##  9 0.22  Fair  E     VS2      65.1    61   337  3.87  3.78  2.49           1532.
## 10 0.23  Very~ H     VS1      59.4    61   338  4     4.05  2.39           1470.
## # ... with 53,930 more rows

pryr::object_size() gives the memory occupied by all of its arguments.

Dapat dilihat pada hasil dibawah diamonds mengkonsumsi 3.46 MB dan diamonds2 mengkonsumsi 3.89 MB.

Karena diamonds adalah bagian diamonds2 yaitu diamonds2 tanpa kolom price_per_carat, maka gabungan dari konsumsi memory dari diamonds dan diamonds2 adalah sebesar diamonds2.

pryr::object_size(diamonds)
## Registered S3 method overwritten by 'pryr':
##   method      from
##   print.bytes Rcpp
## 3.46 MB
pryr::object_size(diamonds2)
## 3.89 MB
pryr::object_size(diamonds, diamonds2)
## 3.89 MB

Bagaimana bila salah satu value pada kolom carat diubah. Hal tersebut mengakibatkan kolom carat pada diamonds dan diamonds2 berbeda, yang mengakibatkan konsumsi memory gabungan diamonds dan diamonds2 berubah (antara diamonds dan diamonds2, kolom price_per_carat berbeda, jelas karena pada diamonds tidak ada. Dan pada kolom carat berbeda).

diamonds$carat[1] <- NA
pryr::object_size(diamonds)
## 3.46 MB
pryr::object_size(diamonds2)
## 3.89 MB
pryr::object_size(diamonds, diamonds2)
## 4.32 MB

pipes (%>%), setahu saya hanya bisa dilakukan pada dataset berbentuk dataframe.


Other Tools from magrittr

When working with more complex pipes, it’s sometimes useful to call a function for its side effects. Maybe you want to print out the current object, or plot it, or save it to disk.

Hasil dibawah hanya menghasilkan grafik saja, padahal merintahkan juga untuk menampilkan data.

rnorm(100) %>%
  matrix(ncol = 2) %>%
  plot() %>%
  str()

##  NULL

To work around this problem, you can use the “tee” pipe. %T>%

rnorm(100) %>%
  matrix(ncol = 2) %T>%
  plot() %>%
  str()

##  num [1:50, 1:2] 1.38 0.33 -0.968 -0.304 0.663 ...

If you’re working with functions that don’t have a data frame– based API (i.e., you pass them individual vectors, not a dataframe and expressions to be evaluated in the context of that dataframe), you might find %$% useful.

mtcars %>% cor(disp, mpg)

code diatas error. karena pipes tidak bisa bekerja pada vector(karena kolom pada data frame bila diambil menjadi vector).

Karena error gak bisa dimasukkin ke chunk, pas di knit error. Antara Kayanya kalau dalam bentuk markdown gak boleh error chunksnya. Atau sayanya aja gak tau inimah.

mtcars %$%
  cor(disp, mpg)
## [1] -0.8475514

For assignment magrittr provides the %<>% operator, which allows you to replace code like:

mtcars <- mtcars %>%
  transform(cyl = cyl * 2)
mtcars
##                      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4           21.0  12 160.0 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag       21.0  12 160.0 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710          22.8   8 108.0  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive      21.4  12 258.0 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout   18.7  16 360.0 175 3.15 3.440 17.02  0  0    3    2
## Valiant             18.1  12 225.0 105 2.76 3.460 20.22  1  0    3    1
## Duster 360          14.3  16 360.0 245 3.21 3.570 15.84  0  0    3    4
## Merc 240D           24.4   8 146.7  62 3.69 3.190 20.00  1  0    4    2
## Merc 230            22.8   8 140.8  95 3.92 3.150 22.90  1  0    4    2
## Merc 280            19.2  12 167.6 123 3.92 3.440 18.30  1  0    4    4
## Merc 280C           17.8  12 167.6 123 3.92 3.440 18.90  1  0    4    4
## Merc 450SE          16.4  16 275.8 180 3.07 4.070 17.40  0  0    3    3
## Merc 450SL          17.3  16 275.8 180 3.07 3.730 17.60  0  0    3    3
## Merc 450SLC         15.2  16 275.8 180 3.07 3.780 18.00  0  0    3    3
## Cadillac Fleetwood  10.4  16 472.0 205 2.93 5.250 17.98  0  0    3    4
## Lincoln Continental 10.4  16 460.0 215 3.00 5.424 17.82  0  0    3    4
## Chrysler Imperial   14.7  16 440.0 230 3.23 5.345 17.42  0  0    3    4
## Fiat 128            32.4   8  78.7  66 4.08 2.200 19.47  1  1    4    1
## Honda Civic         30.4   8  75.7  52 4.93 1.615 18.52  1  1    4    2
## Toyota Corolla      33.9   8  71.1  65 4.22 1.835 19.90  1  1    4    1
## Toyota Corona       21.5   8 120.1  97 3.70 2.465 20.01  1  0    3    1
## Dodge Challenger    15.5  16 318.0 150 2.76 3.520 16.87  0  0    3    2
## AMC Javelin         15.2  16 304.0 150 3.15 3.435 17.30  0  0    3    2
## Camaro Z28          13.3  16 350.0 245 3.73 3.840 15.41  0  0    3    4
## Pontiac Firebird    19.2  16 400.0 175 3.08 3.845 17.05  0  0    3    2
## Fiat X1-9           27.3   8  79.0  66 4.08 1.935 18.90  1  1    4    1
## Porsche 914-2       26.0   8 120.3  91 4.43 2.140 16.70  0  1    5    2
## Lotus Europa        30.4   8  95.1 113 3.77 1.513 16.90  1  1    5    2
## Ford Pantera L      15.8  16 351.0 264 4.22 3.170 14.50  0  1    5    4
## Ferrari Dino        19.7  12 145.0 175 3.62 2.770 15.50  0  1    5    6
## Maserati Bora       15.0  16 301.0 335 3.54 3.570 14.60  0  1    5    8
## Volvo 142E          21.4   8 121.0 109 4.11 2.780 18.60  1  1    4    2
mtcars %<>% transform(cyl = cyl * 2)
mtcars
##                      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4           21.0  24 160.0 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag       21.0  24 160.0 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710          22.8  16 108.0  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive      21.4  24 258.0 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout   18.7  32 360.0 175 3.15 3.440 17.02  0  0    3    2
## Valiant             18.1  24 225.0 105 2.76 3.460 20.22  1  0    3    1
## Duster 360          14.3  32 360.0 245 3.21 3.570 15.84  0  0    3    4
## Merc 240D           24.4  16 146.7  62 3.69 3.190 20.00  1  0    4    2
## Merc 230            22.8  16 140.8  95 3.92 3.150 22.90  1  0    4    2
## Merc 280            19.2  24 167.6 123 3.92 3.440 18.30  1  0    4    4
## Merc 280C           17.8  24 167.6 123 3.92 3.440 18.90  1  0    4    4
## Merc 450SE          16.4  32 275.8 180 3.07 4.070 17.40  0  0    3    3
## Merc 450SL          17.3  32 275.8 180 3.07 3.730 17.60  0  0    3    3
## Merc 450SLC         15.2  32 275.8 180 3.07 3.780 18.00  0  0    3    3
## Cadillac Fleetwood  10.4  32 472.0 205 2.93 5.250 17.98  0  0    3    4
## Lincoln Continental 10.4  32 460.0 215 3.00 5.424 17.82  0  0    3    4
## Chrysler Imperial   14.7  32 440.0 230 3.23 5.345 17.42  0  0    3    4
## Fiat 128            32.4  16  78.7  66 4.08 2.200 19.47  1  1    4    1
## Honda Civic         30.4  16  75.7  52 4.93 1.615 18.52  1  1    4    2
## Toyota Corolla      33.9  16  71.1  65 4.22 1.835 19.90  1  1    4    1
## Toyota Corona       21.5  16 120.1  97 3.70 2.465 20.01  1  0    3    1
## Dodge Challenger    15.5  32 318.0 150 2.76 3.520 16.87  0  0    3    2
## AMC Javelin         15.2  32 304.0 150 3.15 3.435 17.30  0  0    3    2
## Camaro Z28          13.3  32 350.0 245 3.73 3.840 15.41  0  0    3    4
## Pontiac Firebird    19.2  32 400.0 175 3.08 3.845 17.05  0  0    3    2
## Fiat X1-9           27.3  16  79.0  66 4.08 1.935 18.90  1  1    4    1
## Porsche 914-2       26.0  16 120.3  91 4.43 2.140 16.70  0  1    5    2
## Lotus Europa        30.4  16  95.1 113 3.77 1.513 16.90  1  1    5    2
## Ford Pantera L      15.8  32 351.0 264 4.22 3.170 14.50  0  1    5    4
## Ferrari Dino        19.7  24 145.0 175 3.62 2.770 15.50  0  1    5    6
## Maserati Bora       15.0  32 301.0 335 3.54 3.570 14.60  0  1    5    8
## Volvo 142E          21.4  16 121.0 109 4.11 2.780 18.60  1  1    4    2

The pipe won’t work for two classes of functions: (saya belum pernah juga make ini jadi belum terlalu paham)

  1. Functions that use the current environment. For example, assign() will create a new variable with the given name in the current environment:, Other functions with this problem include get() and load().
assign("x", 10)
x
## [1] 10
"x" %>% assign(100)
x # harusnya 100
## [1] 10

If you do want to use assign with the pipe, you must be explicit about the environment:

env <- environment()
"x" %>% assign(100, envir = env)
x
## [1] 100
  1. Functions that use lazy evaluation. In R, function arguments are only computed when the function uses them, not prior to calling the function. There are a relatively wide class of functions with this behavior, including try(), suppressMessages(), and suppressWarnings() in base R.
tryCatch(stop("!"), error = function(e) "An error")
## [1] "An error"

stop(“!”) %>% tryCatch(error = function(e) “An error”)

Ini juga error.


Semoga Bermanfaat