27

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?

0

4 Answers 4

43

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
3
  • 1
    What if I need it just in one row, and I have several?
    – skan
    Oct 20, 2010 at 14:31
  • 7
    @user425895: Then you need to specify that in your question. Oct 20, 2010 at 14:39
  • 2
    Modern variant: withr::with_options(c(scipen = 10), write.table(foo, "foo.txt"). Jul 19, 2016 at 13:42
20

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.

3
  • 1
    I should probably mention that using quote = FALSE will stop all character and factor columns being quoted. Oct 20, 2010 at 17:08
  • 2
    I'm passing csv files to a postgres database. The default sql won't recognize 1e+5 as an integer...
    – Rodrigo
    Sep 3, 2015 at 18:05
  • For instance Circos (circos.ca) requires non-scientific formatting. Therefore, I would guess, that Perl does not consider scientific numbers as integers. Jul 19, 2016 at 10:24
6

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), ...)
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.