magrittr是一個提供 pipe-operator 的套件,該套件裡包含了 4 個 pipe-operator,分別是%>%、%T>% 、%<>%、%$%。pipe-operator的好處就是可以讓程式碼增加可讀性,也不會發生寫一長串程式碼時找不到小括號哪裡括錯的尷尬情況。
1. “%>%" (forward-pipe operator) 是將 lhs (left hand side) 的物件丟到 rhs (right hand side)的函數裡當輸入,回傳的是 rhs 的結果。
2. “%T>%" (tee operator) 也是將 lhs 的物件丟到 rhs 的函數裡當輸入,但回傳的是lhs 的原本輸入值,並非 rhs 的結果,在 rhs 為 plot()、print() …等沒有回傳值的函數時才會用到。
3. “%<>%" (compound assignment pipe-operator) 將 lhs 的物件丟到 rhs 當輸入並且把 rhs 的結果 assign 到 lhs。
4. “%$%" (exposition pipe-operator) 將 lhs 的 data.frame、enviroment 或 list 裡的物件取出到 rhs 的函數當輸入,並回傳 rhs 的結果。
另外magrittr 裡也改寫了常用的基本函數讓 pipe-operator 可以更流暢的使用。還有在pipeline的程式碼常常會出現 “." 代表 lhs 的物件。
> library(magrittr) > > x <- 1:5 > > # %>% > as.integer(2*sqrt(x)) # normal [1] 2 2 3 4 4 > > x %>% sqrt %>% multiply_by(2) %>% as.integer # pipeline [1] 2 2 3 4 4 > > # %T>% > print(x) ;x^2 # normal [1] 1 2 3 4 5 [1] 1 4 9 16 25 > > x %T>% print() %>% raise_to_power(2) # pipeline [1] 1 2 3 4 5 [1] 1 4 9 16 25 > > # %<>% > x <- x + 1 ;x # normal [1] 2 3 4 5 6 > > x %<>% add(1) ;x # pipeline [1] 3 4 5 6 7 > > # %$% > x.data <- data.frame(a = 1:10, b = 11:20) # normal > x.data[which(x.data$a >5 & x.data$b <19),] # normal a b 6 6 16 7 7 17 8 8 18 > > data.frame(a = 1:10, b = 11:20) %$% .[which(a > 5 & b < 19),] # pipeline a b 6 6 16 7 7 17 8 8 18