[R] Different decimal places in a matrix

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu Jul 29 20:48:20 CEST 2010


On 29-Jul-10 09:25:37, Ted Harding wrote:
> On 29-Jul-10 09:08:22, Nicola Sturaro Sommacal wrote:
>> Hi!
>> I have a ftable object in which some row contains integers and
>> some other contains a percentage that I would like to show with
>> two digits after the dot.
>> 
>> I tried something like
>> ftblP[index,] = as.character(round(ftblP[index,],2))
>> where the index vector contains the number of the rows containing a
>> percentage. My workaround works but it shows all numbers aligned to
>> left, while I prefer that number will be aligned "correctly" (to
>> the right).
>> 
>> It is possible?
>> 
>> Thanks in advance.
>> Nicola S.
> 
> Interesting question! I take it you want to see something like
> 
>   49      21     166
>   12.21    6.75   49.65
> 
> The "raw" approach I would suggest is to "pack" the integers
> on the right with 3 blanks. I think it should be possible to
> do this with sprintf(). using different 'fmt' specifications
> for the "integer" rows and the "percentage" rows, and using
> cat() to output the results. However, I don't have time right
> now to explore the details of how it might be done. Sorry.
> 
> Ted.

Well, I've got something to work along the lines I suggested.
Example:


N <- c(21,33,145,18,102)   # Integers
P <- 100*N/sum(N)          # Percebtages

## [A]: decimal alignment
cat(rbind(paste(c(sprintf("%4.0f     ",N),"\n"),collapse=""),
          paste(c(sprintf("%6.2f   ",P),"\n"),collapse="")))
## Result:
#    21       33      145       18      102
#     6.58    10.34    45.45     5.64    31.97


## [B]: right-justified alignment
cat(rbind(paste(c(sprintf("%7.0f  ",N),"\n"),collapse=""),
          paste(c(sprintf("%6.2f   ",P),"\n"),collapse="")))
## Result:
#      21       33      145       18      102
#    6.58    10.34    45.45     5.64    31.97


I'm sure there's someone who can improve on this!
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 29-Jul-10                                       Time: 19:48:18
------------------------------ XFMail ------------------------------



More information about the R-help mailing list