Search code examples
rboxplotmedianextractquartile

How to extract and format Median and IQR from a boxplot


I wish to extract and format the median and interquartile range from my boxplot stat.

I managed to get the raw results with this line of code:

b <- boxplot(len ~ dose, data = ToothGrowth)
b$stats

Which gives me :

      [,1]  [,2]  [,3]
[1,]  4.20 13.60 18.50
[2,]  7.15 16.00 23.45
[3,]  9.85 19.25 25.95
[4,] 13.00 23.45 28.35
[5,] 21.50 27.30 33.90

I can exact one row or one column separately adding [,1] or [1,], ie : I can extract min/1st quartile/median/3rd quartile/max for one group OR one stat for each subgroup by example :

> b$stats[2,]
[1]  7.15 16.00 23.45
> b$stats[,2]
[1] 13.60 16.00 19.25 23.45 27.30

but I can't figure a simple way to extract and format median and IQR for each subgroups [,1] [,2] and [,3] to get something like this :

[,1] median [lower quartile-upper quartile].

I could do it manually but I have hundreds of variable to save... Any suggestion would be much appreciated! Thank by advance


Solution

  • If you are using boxplot, take a look at list(b), which will provide you with a list of outputs. Now to get median and IQR, that is going to be rows 3 (for median) and 2,4 (for IQR bounds).

    med <- round(b$stats[3, ], 2) #median
    liqr<- round(b$stats[2, ], 2) #lower IQR
    uiqr<- round(b$stats[4, ], 2) #upper IQR
    

    Now based on your expected output, you will probably want to use some form of paste as

    output <- paste0(med, " [", liqr,"-" ,uiqr,"]")
    

    Hope this helps.