Number format, writing 1e-5 instead of 0.00001

前端 未结 4 543
难免孤独
难免孤独 2020-12-03 10:25

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 a

相关标签:
4条回答
  • 2020-12-03 10:38

    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.

    0 讨论(0)
  • 2020-12-03 10:38

    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
    
    0 讨论(0)
  • 2020-12-03 10:53

    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), ...)
    
    0 讨论(0)
  • 2020-12-03 10:56

    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")
    
    0 讨论(0)
提交回复
热议问题