Formatting Decimal places in R

前端 未结 12 2064
忘了有多久
忘了有多久 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:10

    Something like that :

    options(digits=2)
    

    Definition of digits option :

    digits: controls the number of digits to print when printing numeric values.
    
    0 讨论(0)
  • 2020-11-22 02:10

    Looks to me like to would be something like

    library(tutoR)
    format(1.128347132904321674821, 2)
    

    Per a little online help.

    0 讨论(0)
  • 2020-11-22 02:16

    if you just want to round a number or a list, simply use

    round(data, 2)
    

    Then, data will be round to 2 decimal place.

    0 讨论(0)
  • 2020-11-22 02:17

    Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.

    0 讨论(0)
  • 2020-11-22 02:21

    Check functions prettyNum, format

    to have trialling zeros (123.1240 for example) use sprintf(x, fmt='%#.4g')

    0 讨论(0)
  • 2020-11-22 02:22

    Background: Some answers suggested on this page (e.g., signif, options(digits=...)) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.

    Solution:

    The following code shows exactly two decimal places for the number x.

    format(round(x, 2), nsmall = 2)
    

    For example:

    format(round(1.20, 2), nsmall = 2)
    # [1] "1.20"
    format(round(1, 2), nsmall = 2)
    # [1] "1.00"
    format(round(1.1234, 2), nsmall = 2)
    # [1] "1.12"
    

    A more general function is as follows where x is the number and k is the number of decimals to show. trimws removes any leading white space which can be useful if you have a vector of numbers.

    specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))
    

    E.g.,

    specify_decimal(1234, 5)
    # [1] "1234.00000"
    specify_decimal(0.1234, 5)
    # [1] "0.12340"
    
    0 讨论(0)
提交回复
热议问题