user7256821
user7256821

Reputation: 69

Modify summary output

I want to modify the summary output returned from summary function (base r):

summary(mtcars)

This shows standard summary stat:

   am              gear            carb      
 Min.   :0.0000   Min.   :3.000   Min.   :1.000  
 1st Qu.:0.0000   1st Qu.:3.000   1st Qu.:2.000  
 Median :0.0000   Median :4.000   Median :2.000  
 Mean   :0.4062   Mean   :3.688   Mean   :2.812  
 3rd Qu.:1.0000   3rd Qu.:4.000   3rd Qu.:4.000  
 Max.   :1.0000   Max.   :5.000   Max.   :8.000

Can I modify this output by removing Median and adding count and stdev? Thanks.

Upvotes: 2

Views: 287

Answers (1)

jay.sf
jay.sf

Reputation: 73782

Make a DIY summary using sapply.

sapply(mtcars[c("am", "gear", "carb")], function(x)
  c(min=min(x), quantile(x, c(.25, .75)), max=max(x), count=length(x), sd=sd(x)))
#               am       gear    carb
# min    0.0000000  3.0000000  1.0000
# 25%    0.0000000  3.0000000  2.0000
# 75%    1.0000000  4.0000000  4.0000
# max    1.0000000  5.0000000  8.0000
# count 32.0000000 32.0000000 32.0000
# sd     0.4989909  0.7378041  1.6152

Alternatively you may use lapply to customize columns by rounding etc.

do.call(rbind, lapply(mtcars[c("am", "gear", "carb")], function(x)
  data.frame(min=min(x), q1=quantile(x, .25), q3=quantile(x, .75), max=max(x), 
             count=length(x), sd=round(sd(x), 3))))
#      min q1 q3 max count    sd
# am     0  0  1   1    32 0.499
# gear   3  3  4   5    32 0.738
# carb   1  2  4   8    32 1.615

Upvotes: 2

Related Questions