[R] a decimal aligned column

Gabor Grothendieck ggrothendieck at gmail.com
Sat Sep 30 18:43:52 CEST 2006


For the last line you could also consider the print.data.frame method:

   data.frame(Symbol = symbols, dolVol = dolVol.pretty)

or

   data.frame(row.names = symbols, dolVol = dolVol.pretty)

capture.output or sink could be used if you want to direct it to a file.

On 9/30/06, BBands <bbands at gmail.com> wrote:
> 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.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list