Rで文字をUnicodeに変えるときはstringiパッケージ


たまに忘れるので備忘録として書いておきます。

Rでパッケージを作るときには日本語(マルチバイト)が使えないので、「プロパティファイルを作って読み込ませたい」みたいなニーズがあるとUnicode変換して持っておく必要があります。

sysdata.rdaとして内部データとして保持しておけば良いという話もありますが、rdaファイルだと一般に公開しないまでもチームでパッケージを共有する際にちょっとした定義文字列を共有できないのでやっぱりプロパティファイルなのかな、ということになります。

そんなときにstringi::stri_escape_unicode()を使用するとエスケープできるので便利ですね。

> library(stringi)
> stri_escape_unicode("こんにちは")
[1] "\\u3053\\u3093\\u306b\\u3061\\u306f"
> stri_unescape_unicode("\\u3053\\u3093\\u306b\\u3061\\u306f")
[1] "こんにちは"

また、前述のプロパティファイルを作ったとして、Javaなどにあるnative2asciiの処理をする関数はこんな感じでしょうか。

hello_native.properties

hello=こんにちは
goodbye=さようなら
read_file_path <- paste(getwd(), "R", "hello_native.properties", sep = "/")
write_file_path <- paste(getwd(), "R", "hello_ascii.properties", sep = "/")
native2ascii <- function(read_file_path, write_file_path){
  write(stringi::stri_escape_unicode(readLines(file_path)),
        file = save_file_path)
}

実行後

hello_ascii.properties

hello=\u3053\u3093\u306b\u3061\u306f
goodbye=\u3055\u3088\u3046\u306a\u3089

Rはシステム化にはちょっと面倒な言語なので一工夫いるかもしれませんがこういう使い方もあるということで。

<iframe style=”width:120px;height:240px;” marginwidth=”0″ marginheight=”0″ scrolling=”no” frameborder=”0″ src=”//rcm-fe.amazon-adsystem.com/e/cm?lt1=_blank&bc1=000000&IS2=1&bg1=FFFFFF&fc1=000000&lc1=0000FF&t=kitamix-22&language=ja_JP&o=9&p=8&l=as4&m=amazon&f=ifr&ref=as_ss_li_til&asins=4873117593&linkId=e8c10e4fc682b2fb5f822fed9026afc8″></iframe>