[R] formatting output

Gabor Grothendieck ggrothendieck at myway.com
Tue Mar 1 02:21:33 CET 2005


Marc Schwartz <MSchwartz <at> MedAnalytics.com> writes:

: 
: On Mon, 2005-02-28 at 14:05 -0400, Peyuco Porras Porras . wrote:
: >    Dear R-users
: > 
: >    A  basic  question  that I wasn't able to solve: Is it possible to get
: >    the  results  of the function 'quantile' expressed as data.frame? What
: >    I'm  doing  is  to  apply the following code to get the quantiles in a
: >    particular dataset:
: > 
: >    tmp<-tapply(data$DEN,list(Age=data$AGE,Sex=data$SEX),quantile)
: > 
: >    and  then I save this output to HTML using the library R2HTML. However
: >    in  order  to  format  the  tables  in  HTML I have to use the command
: >    HTML.data.frame(...)  which  allows  me  to  define,  for example, the
: >    number of digits in the html table.

Note that HTML has numerous methods, not just HTML.data.frame.  Issue
the command:

  methods(HTML)

to see them.

: > 
: >    But  the object 'tmp' is not a dataframe and I can't coarce it to this
: >    format.  Is  it  possible  to  get  the  results of this function as a
: >    dataframe? I  know  that  I'm probably missing some important concepts
: >    here but Im not very good in programming.
: > 
: >    Any hint will be appreciated
: 
: Here is one approach, using an expansion of one of the examples in
: ?tapply:
: 
: # Get quantiles of 'breaks' for each combination of 'wool' and 'tension'
: > my.tmp <- tapply(warpbreaks$breaks, 
:                    list(warpbreaks$wool, warpbreaks$tension), quantile)
: 
: # Note that my.tmp is a 2 x 6 matrix of list elements
: # with each list element being the results of quantile
: # on each combination of 'wool' and 'tension'
: 
: > my.tmp
:   L         M         H
: A Numeric,5 Numeric,5 Numeric,5
: B Numeric,5 Numeric,5 Numeric,5
: 
: For example:
: 
: > my.tmp[1, 1]
: [[1]]
:   0%  25%  50%  75% 100%
:   25   26   51   54   70
: 
: Now get this into a manageable structure by taking each list element in
: my.tmp and converting it into a row in a new matrix, use:
: 
: > my.mat <- do.call("rbind", my.tmp)
: 
: > my.mat
:      0% 25% 50% 75% 100%
: [1,] 25  26  51  54   70
: [2,] 14  20  29  31   44
: [3,] 12  18  21  30   36
: [4,] 16  21  28  39   42
: [5,] 10  18  24  28   43
: [6,] 13  15  17  21   28
[...snipped off code to add row names...]

Here is a slight variation of Marc's solution that avoids explicit
setting of the row names:

R>   my.tmp <- split(warpbreaks$breaks, 
+     list(warpbreaks$wool, warpbreaks$tension))
R>   my.tmp <- lapply(my.tmp, quantile)
R>   do.call("rbind", my.tmp)
    0% 25% 50% 75% 100%
A.L 25  26  51  54   70
B.L 14  20  29  31   44
A.M 12  18  21  30   36
B.M 16  21  28  39   42
A.H 10  18  24  28   43
B.H 13  15  17  21   28




More information about the R-help mailing list