LoginSignup
2
2

More than 5 years have passed since last update.

Rの関数を%>%でつなげるsyntax sugar

Posted at

Context

  • Rでdplyrなどを使いデータ処理を行う際に、%>%でつなげて文字列の置換でgsub関数を使おうとすると引数の順番がアレなので使いにくい。
  • %>% でつなげられるようにsyntax sugarをかませる。

コード

library(dplyr)

# 名前空間を整理するために、関数名をモジュールライクに定義する。
Utils.gsub <- function(str,target,replace){ gsub(target,replace,str) }

x <- "hoge"
y <- x %>% Utils.gsub("h","b")   # => "boge"

課題

  • 同じような形でsyntax sugarにすることで使いやすくなる関数は多いはず。
  • 些細なネタではあるものの、ソースコードの可読性を高める(カッコの対応が読みにくい!)には意外と効果がある。
  • 追加次第編集予定(?)。
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2