LoginSignup
0
0

More than 1 year has passed since last update.

A.変数の中にある数字を使ってグループ化したい

Last updated at Posted at 2021-12-04

さて,解決編。

私はこうしました。

sample <- data.frame(
  name = c("theta.1.1","gamma.1.2","theta.2.1","lambda.2.2"),
  value = c(0.120,0.0796,0.584,0.264)
)

sample %>%
  mutate(
    variables = str_split_fixed(name, pattern = "\\.", n = 3)[, 1],
    val1 = str_split_fixed(name, pattern = "\\.", n = 3)[, 2],
    val2 = str_split_fixed(name, pattern = "\\.", n = 3)[, 3]
  )

とりあえず文字列処理ですから,stringrとかstringiパッケージのお世話になるのは確定ですよね。
で,stringiパッケージのstr_split_fixedで,ピリオドをキーにして3つの要素に分けます。ピリオドはそのままだと記号じゃなく第一引数の意味になっちゃうから,\\でエスケープします。

ここで次のようにしても,見た目にはそれっぽくなるんです。

sample %>%
  mutate(
    variables = str_split_fixed(name, pattern = "\\.", n = 3))

が,実はこれ,変数nameが複数の要素を持っている変なデータフレームなので美しくない。

     [,1]     [,2] [,3]
[1,] "theta"  "1"  "1" 
[2,] "gamma"  "1"  "2" 
[3,] "theta"  "2"  "1" 
[4,] "lambda" "2"  "2" 

なので,作る時に列の要素も指定してやらないといけない。それが[,1]とか[,2],[,3]のところですね。

あんまり美しくない答えかもしれないんですけど,私はこれしか思いつかないのでこうしてます。

こんな感じで,自分のTips,こんなバグをこうやって解決したよ,というような話を,よろしければ皆さんもお寄せください。
出題編はこちらです。
あるいは「こちらの解法のほうが美しいぞ」というのがありましたら,コメントいただけると幸いです。

0
0
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
0
0