LoginSignup
2

More than 5 years have passed since last update.

posted at

updated at

R: summary(df) の出力を tbl_df に変換するスマートな方法

summary(df)dfを要約してくれる便利な関数ですが、
出力がtableなのでそのままでは使いにくいことがあります。

以外に面倒なtbl_df(or data.frame) への変換方法をメモしておきます。

as.matrix()ではtablematrixに変換できないので、
手っ取り早い方法としてrbind()を使っています。
(これは、class(table_obj) <- NULL と同義です)。

library(tidyverse)

iris %>%
  summary() %>%                       # なにはともあれsummary()
  rbind() %>%                         # matrix化
  magrittr::set_rownames(NULL) %>%    # 行名""を削除
  as.tibble() %>%                     # tbl_df化
  map_dfr(~ str_trim(.)) %>%          # 要素の前後空白を削除
  set_names(str_trim(names(.)))       # 列名の前後空白を削除

割とよく使うので私は関数化しています。

summary2tbl <- function(summary_table) {
  summary_table %>% 
    rbind() %>% 
    magrittr::set_rownames(NULL) %>% 
    as.tibble() %>% 
    map_dfr(~ str_trim(.)) %>% 
    set_names(str_trim(names(.)))
}
iris %>% 
  summary() %>% 
  summary2tbl()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 setosa :50
1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 versicolor:50
Median :5.800 Median :3.000 Median :4.350 Median :1.300 virginica :50
Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199 NA
3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 NA
Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 NA

Let's enjoy !!

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
What you can do with signing up
2