Number format, writing 1e-5 instead of 0.00001

▼魔方 西西 提交于 2019-12-28 03:01:08

问题


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?


回答1:


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.




回答2:


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:


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



回答4:


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


来源:https://stackoverflow.com/questions/3978266/number-format-writing-1e-5-instead-of-0-00001

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!