Martin
Martin

Reputation: 1640

Restructure output of R summary function

Is there an easy way to change the output format for R's summary function so that the results print in a column instead of row? R does this automatically when you pass summary a data frame. I'd like to print summary statistics in a column when I pass it a single vector. So instead of this:

>summary(vector)

Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
1.000   1.000   2.000   6.699   6.000 559.000 

It would look something like this:

  >summary(vector)

    Min.    1.000
    1st Qu. 1.000 
    Median  2.000  
    Mean    6.699
    3rd Qu. 6.000   
    Max.    559.000

Upvotes: 3

Views: 3420

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

Sure. Treat it as a data.frame:

set.seed(1)
x <- sample(30, 100, TRUE)

summary(x)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#    1.00   10.00   15.00   16.03   23.25   30.00 
summary(data.frame(x))
#        x        
#  Min.   : 1.00  
#  1st Qu.:10.00  
#  Median :15.00  
#  Mean   :16.03  
#  3rd Qu.:23.25  
#  Max.   :30.00

For slightly more usable output, you can use data.frame(unclass(.)):

data.frame(val = unclass(summary(x)))
#           val
# Min.     1.00
# 1st Qu. 10.00
# Median  15.00
# Mean    16.03
# 3rd Qu. 23.25
# Max.    30.00

Or you can use stack:

stack(summary(x))
#   values     ind
# 1   1.00    Min.
# 2  10.00 1st Qu.
# 3  15.00  Median
# 4  16.03    Mean
# 5  23.25 3rd Qu.
# 6  30.00    Max.

Upvotes: 5

Related Questions