tags:

views:

112

answers:

4

Hello

I've used read.table to read a file that contains numbers such as 0.00001

when I write them back with write.table those numbers appear as 1e-5

How can I keep the old format?

thanks

+3  A: 

If the input is a mixture of scientific notation and explicit notation numbers, then you will be writing your own parser to read in the numbers and keep track of which ones were in which formats. In fact, you'll want to keep a string representation of those numbers lying around so you can write back exactly what was in the input.

However, if you just want to write.table() with consistently explicit notation, try.

    write.table(format(_your_table_here_, scientific=FALSE), ...)
Eric Towers
+1  A: 

You can do this by converting your numbers to strings with formatting as you require, then using the argument quote = FALSE in the call to write.table.

dfr <- data.frame(x = 10^(0:15))
dfr$y <- format(dfr$x, scientific = FALSE)
write.table(dfr, file = "test.txt", quote = FALSE)

Note that you shouldn't need to change the format of the numbers in your file. Pretty much every piece of scientific software and every spreadsheet understands scientific notation for numbers, and also has number formatting options so you can view them how you choose.

Richie Cotton
I should probably mention that using `quote = FALSE` will stop **all** character and factor columns being quoted.
Richie Cotton
+5  A: 

I would just change the scipen option before calling write.table. Note that this will also change how numbers are displayed when printing to the console.

options(scipen=10)
write.table(foo, "foo.txt")
options(scipen=0)  # restore the default
Joshua Ulrich
What if I need it just in one row, and I have several?
@user425895: Then you need to specify that in your question.
Joshua Ulrich
A: 

For maximum control loop over all rows and print them to a text file formatted with sprintf

# Find number of rows in data.frame test
nrows <- dim(test)[1]

# init a new vector
mylines  <- vector("character",dim(test)[1])

# loop over all rows in dataframe
for(i in 1:nrows){
  # Print out exactly the format you want
  mylines[i] <- sprintf("Line %d: %.2f\t%.2f",1,test[i,"x"],test[i,"y")
}

# write lines to file
writeLines(mylines,"out.txt")
Henrik