メモ:Rでemojiを扱うにはどうすれば...
こういう問題に悩まされていて、どうすればいいか調べる途中のメモ
具体的に言うとこのエラーをなんとかしたい。
# devtools::install_github("hadley/emo") wm <- emo::ji("watermelon") as.character(wm) #> [1] "\xf0\u009f\u008d\u0089" gregexpr(".", as.character(wm), perl = TRUE) #> Error in gregexpr(".", as.character(wm), perl = TRUE) : #> invalid input '拷' in 'utf8towcs'
この\xf0
とか\u009f
という文字列の書き方は、?Quote
を見れば書かれている。
\nnn character with given octal code (1, 2 or 3 digits) \xnn character with given hex code (1 or 2 hex digits) \unnnn Unicode character with given code (1--4 hex digits) \Unnnnnnnn Unicode character with given code (1--8 hex digits)
続けて引用。
Unicode escapes can be used to enter Unicode characters not in the current locale’s charset (when the string will be stored internally in UTF-8).
今のロケール(SJIS)にない文字はUnicode escapeで表すことができる。なので、emojiは
as.character(emo:::ji("question")) [1] "\u2753"
のような表記としてみることができる。
↑ちなみに、このemoパッケージというのはHadleyのやつ。
とりあえずemojiが全部入ってて便利。具体的なデータはemo:::emoji_name
にある。
ただし、上のquestion
のように単純な絵文字ばかりではなく、もっとバイト数が長いやつもある。
wm <- emo::ji("watermelon") wm #> 🍉 as.character(wm) #> [1] "\xf0\u009f\u008d\u0089"
ただしこれは、同じものを直接コンソールに打ち込もうとするとエラーになる。
"\xf0\u009f\u008d\u0089" #> Error: mixing Unicode and octal/hex escapes in a string is not allowed
?Quote
を見ると次のような制約があるらしい。
The parser does not allow the use of both octal/hex and Unicode escapes in a single string.
全部\xnn
の記法で書くと次のようなかたち。
"\xf0\x9f\x8d\x89" #> [1] "拷"
これは一見さっきのemojiと違うように見えるけど、文字コードを合わせてやれば同じことがわかる。
`Encoding<-`("\xf0\x9f\x8d\x89", "UTF-8") #> [1] "\xf0\u009f\u008d\u0089"
じゃあこういう書き方でもいけるのでは?という気がしたけどこれだとむりだった。
"\uf09f\u8d89" #> [1] "趉" "\u00f0\u009f\u008d\u0089" #> [1] "ð\u009f\u008d\u0089"
stringiによるとこうらしい。
stringi::stri_escape_unicode(wm) #> [1] "\\U0001f349"
しかし、これをバイト単位で見比べてみるとどうも違う。
# これがもとのやつ charToRaw(wm) #> [1] f0 9f 8d 89 # 表示できないし実際バイト列も違う "\U0001f349" #> [1] "" charToRaw("\U0001f349") #> [1] ef 8d 89
ということで、もうちょっとunicodeのフォーマットについて勉強する必要がありそう。奥が深い…