Formatting Decimal places in R

前端 未结 12 2231
忘了有多久
忘了有多久 2020-11-22 01:42

I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that?

12条回答
  •  忘了有多久
    2020-11-22 02:06

    You can try my package formattable.

    > # devtools::install_github("renkun-ken/formattable")
    > library(formattable)
    > x <- formattable(1.128347132904321674821, digits = 2, format = "f")
    > x
    [1] 1.13
    

    The good thing is, x is still a numeric vector and you can do more calculations with the same formatting.

    > x + 1
    [1] 2.13
    

    Even better, the digits are not lost, you can reformat with more digits any time :)

    > formattable(x, digits = 6, format = "f")
    [1] 1.128347
    

提交回复
热议问题