LoginSignup
11
10

More than 5 years have passed since last update.

dplyr でグループごとに複数カラムを追加したい #rstatsj

Last updated at Posted at 2015-03-18

dplyr でグループごとの quantile をカラムに追加したくなったんですが、複数カラムを追加する方法がよくわかりませんでした。

例えば、iris データに対して、Species ごとの Sepal.Lengthquantile が知りたかったとします。

それはこのようにすれば一応は結果が見れるんですが、

R
iris %>% group_by(Species) %>% 
  summarize(sepal_length_quantile = quantile(Sepal.Length) %>% list %>% as.character)
結果
     Species        sepal_length_quantile
1     setosa     c(4.3, 4.8, 5, 5.2, 5.8)
2 versicolor     c(4.9, 5.6, 5.9, 6.3, 7)
3  virginica c(4.9, 6.225, 6.5, 6.9, 7.9)

やはりこの sepal_length_quantile を複数列に分けて見たいですよね。

色々やり方を試してみて、下記に落ち着きました。

R
iris %>% group_by(Species) %>% 
  summarize(sepal_length_quantile = quantile(Sepal.Length) %>% list) %>%
  cbind(do.call(rbind, .$sepal_length_quantile)) %>%
  select(-sepal_length_quantile)
結果
     Species  0%   25% 50% 75% 100%
1     setosa 4.3 4.800 5.0 5.2  5.8
2 versicolor 4.9 5.600 5.9 6.3  7.0
3  virginica 4.9 6.225 6.5 6.9  7.9

一旦リストとして保存して、do.callmatrix を作り、cbind で結合するという方法です。

ちなみに、リストとして保存するところは dplyr::do を使った方が正式かもしれません。

R
iris %>% group_by(Species) %>% 
  do(sepal_length_quantile = quantile(.$Sepal.Length)) %>%
  cbind(do.call(rbind, .$sepal_length_quantile)) %>%
  select(-sepal_length_quantile)
結果
     Species  0%   25% 50% 75% 100%
1     setosa 4.3 4.800 5.0 5.2  5.8
2 versicolor 4.9 5.600 5.9 6.3  7.0
3  virginica 4.9 6.225 6.5 6.9  7.9

enjoy!

追記

11
10
0

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
11
10