Java Mailing List Archive

http://www.r-help.com/

Home » Home (12/2007) » R Help for Statistical Computing »

Re: [R] formatting output

Marc Schwartz

2005-02-28

Replies:

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.
>
>   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


>From there, you can set the rownames for the matrix, as you require,
based upon the combinations of the vectors in your data. For example,
using expand.grid():

> my.names <- expand.grid(dimnames(my.tmp))

> my.names
Var1 Var2
1   A   L
2   B   L
3   A   M
4   B   M
5   A   H
6   B   H

> rownames(my.mat) <- paste(my.names$Var1, my.names$Var2, sep = ":")

> my.mat
  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


There might be an easier way, but that's my quick thought.

HTH,

Marc Schwartz

______________________________________________
R-help@(protected)
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
©2008 r-help.com - Jax Systems, LLC, U.S.A.