[R] Writing to a file with fixed precision

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Oct 11 09:42:50 CEST 2005


On Mon, 10 Oct 2005, Marc Schwartz wrote:

> On Mon, 2005-10-10 at 19:50 -0400, Richard Hedger wrote:
>> Hi,
>> I'm trying to ouput to a filled with a fixed precision:
>> eg. if I have data x=c(1.0,1.4,2.0), I want to be able to ouput the following to a file:
>> 1.00000000000000
>> 1.40000000000000
>> 2.00000000000000
>> I was wondering if there was a function to do this in R?
>> Thanks,
>> Richard
>
> It is possible that someone has written such a function somewhere.

It's called format().

x <- c(1.0,1.4,2.0)
write(format(x, nsmall=14))

does this.

> However, this is relatively easy using write.table(). You just need to
> pre-format the numeric values prior to writing to the file:
>
> write.table(sprintf("%.14f", x), "data.txt", col.names = FALSE,
>            row.names = FALSE, quote = FALSE)
>
> Using sprintf(), we force the floats to have 14 decimal places.
> sprintf() outputs character vectors, so we remove the quoting of the
> resultant character vectors and don't write column/row names.
>
> Note that if 'x' is a matrix, using sprintf() will return a vector. So
> you might want to use the following instead to retain the dims:
>
>> x
>     [,1] [,2] [,3] [,4]
> [1,]    1    4    7   10
> [2,]    2    5    8   11
> [3,]    3    6    9   12
>
>> x.fmt <- apply(x, 1, function(x) sprintf("%.14f", x))
>
>> x.fmt
>     [,1]                [,2]                [,3]
> [1,] "1.00000000000000"  "2.00000000000000"  "3.00000000000000"
> [2,] "4.00000000000000"  "5.00000000000000"  "6.00000000000000"
> [3,] "7.00000000000000"  "8.00000000000000"  "9.00000000000000"
> [4,] "10.00000000000000" "11.00000000000000" "12.00000000000000"
>
>> write.table(x.fmt, "data.txt", col.names = FALSE, row.names = FALSE,
>              quote = FALSE)
>
>
> If needed, you can of course change the default delimiter from a " " to
> another character in write.table().
>
> See ?write.table and ?sprintf.

-- 
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