[R] a decimal aligned column

BBands bbands at gmail.com
Sat Sep 30 18:07:21 CEST 2006


As requested:

The alignment problem came from calling format many times. Marc
Schwartz suggested a solution of putting my results in a vector and
then formatting. As I understand it the problem is that fixed-width
fields are only available from sprintf, while comma delineation is
only available from format, formatC and prettyNum. The
interrelationships are complicated (format calls prettyNum) and
require _very_ careful study. Here is Marc's solution with a few
changes. It left aligns the symbols and truncates, right aligns and
comma delineates the numbers. In short you get a nice table that is
easy to scan.

If I had one wish for format, it would be that it could set fixed
field width as well as minimum.

library(tseries)
# the symbols
symbols <- c('spy', 'ise', 'oih', 'mot', 'pbj', 'qqqq')
# set the start date to a year ago
Start <- Sys.Date() - 366
# Pre-allocate dolVol as a vector
dolVol <- numeric(length(symbols))
# Now get the values, assign to dolVol by indexing
for(line in seq(along = symbols))
{
 a <- get.hist.quote(instrument=symbols[line], start=Start,
                     compression="w", quote=c("Close", "Volume"),
                     quiet=TRUE)

 dolVol[line] <- mean(a[,1]) * mean(a[,2])
}
# Now for the initial common formatting,
# truncating the dolVol values to whole numbers
dolVol.pretty <- format(trunc(dolVol), big.mark=",", scientific=FALSE,
                       justify="right", width=15)
# Now output
cat(paste(sprintf('%-4s',symbols), dolVol.pretty,
    collapse = "\n", sep = ""), "\n")

spy      8,770,399,023
ise         21,296,087
oih      1,415,206,983
mot        416,923,148
pbj            246,700
qqqq     4,077,543,493

    jab
-- 
John Bollinger, CFA, CMT
www.BollingerBands.com

If you advance far enough, you arrive at the beginning.



More information about the R-help mailing list