[R] How to remove extra spaces introduced (?) by write.table

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Dec 10 12:54:53 CET 2003


Just convert to character before using write.table:

> as.character(c(1, 10))
[1] "1"  "10"

whereas

> format(c(1,10))
[1] " 1" "10"

is what you are seeing.

On Wed, 10 Dec 2003, Valtteri Wirta wrote:

> Dear Group,
> 
> My question relates to the write.table function.
> 
> I have created a data.frame containing both "character" and "numeric" columns.
> When I use the write.table function to write this table into a text file 
> spaces are added into the "numeric" columns so that the number of digits in 
> each column is the same. This extra space is added before the actual number.
> 
> I write the table using the following command:
> write.table(out.obj, sep="\t", file="test.txt", row.names=FALSE, na="NaN", 
> quote=FALSE)
> where out.obj is the data.frame
> 
> A simplified example with three columns
> Sample1\t10\t10
> Sample2\t*1\t*1
> 
> The * denotes the extra space, \t is the tab used as separator
> (a real example can be found at 
> http://biobase.biotech.kth.se/~valtteri/test.txt)
> 
> I need to remove these spaces as they are not compatible with the 
> down-stream application. I'd prefer not to remove these manually using for 
> example MS-Word as the number of files generated is fairly large.
> 
> I verified the modes of the problematic columns and they are, as expected, 
> "numeric".
> 
> My question is how to remove these extra spaces?
> SUB did not work (good for "character" vectors).
> 
> 
> I'm using R.1.8.0 running under Windows XP
> A saved copy of the data.frame can be found at 
> http://biobase.biotech.kth.se/~valtteri/test.RData
> (saved with ascii=TRUE)
> 
> 
> All help is appreciated.
> 
> Thanks,
> 
> Valtteri
> 
> 
> 
> 
> 
> Contact information:
> 
> Valtteri Wirta
> Department of Biotechnology, KTH
> AlbaNova University Center
> S - 10691 Stockholm, Sweden
> 
> Visiting address: Roslagstullsbacken 21, B3
> Phone: +46 8 5537 8344(office)
> Phone: +46 733 386 341 (gsm)
> Fax: +46 8 5537 8481
> Email: valtteri at biotech.kth.se
> Web: www.biotech.kth.se/molbio
> MSN messenger: valzu at hotmail.com
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list