[R] Get rid of space padding

Gene Cutler gcutler at amgen.com
Thu Dec 23 01:09:29 CET 2004


I'm currently using the below function from some library (MASS?) for
writing my data out to file.  I'm using it instead of plain old "write"
because it does buffering.  The problem that I'm having is that the
numbers are space padded, but I need true tab-delineated files.  It
looks like the spaces are coming from 'format', but I don't see
an option for format to not pad numbers, the closest I see has to do
with stripping spaces from strings.  Am I missing something obvious?


write.matrix <- function (x, file = "", sep = "\t", blocksize=2000)
{
     x <- as.matrix(x)
     p <- ncol(x)
     cn <- colnames(x)
     if (!missing(blocksize) && blocksize > 0) {
         cat(cn, file = file, sep = c(rep(sep, p - 1), "\n"))
         nlines <- 0
         nr <- nrow(x)
         while (nlines < nr) {
             nb <- min(blocksize, nr - nlines)
             cat(format(t(x[nlines + (1:nb), ])), file = file,
                 append = TRUE, sep = c(rep(sep, p - 1), "\n"))
             nlines <- nlines + nb
         }
     }
     else cat(c(cn, format(t(x))), file = file, sep = c(rep(sep, p - 1), 
"\n"))
}


Thanks.


-- Gene




More information about the R-help mailing list