【问题标题】:Formatting decimal places with R用 R 格式化小数位
【发布时间】:2020-10-28 01:22:03
【问题描述】:

我有一位数字。它们可能在小数点后有 0、1 或 2 位。

我希望至少显示一位小数。因此:

2 显示为 2.0

如果有一位小数,请显示,但不要添加额外的零。所以:

2.1 显示为 2.1

如果有两位小数,请同时显示:

2.45 显示为 2.45

鉴于x <- c(1.8, 1.55, 1.5, 1) 我应该得到(1.8, 1.55, 1.5, 1.0)

sprintfformat 可以做到这一点吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    这可以通过结合formatsub 来实现

    > x <- c(1.8, 1.55, 1.5, 1, 1.23445, 100, -1)
    # the pattern (?<=\\.\\d)0$ checks if the last number after . is a zero if so replace with nothing
    > sub("(?<=\\.\\d)0$", "", format(x, digits=3), perl=T )
    [1] "  1.8"  "  1.55" "  1.5"  "  1.0"  "  1.23" "100.0"  " -1.0" 
    > sub("(^ *)(?=\\d)", "\\1+", sub("(?<=\\.\\d)0$", "", format(x, digits=3), perl=T ), perl=T)
    [1] "  +1.8"  "  +1.55" "  +1.5"  "  +1.0"  "  +1.23" "+100.0"  " -1.0"  
    

    【讨论】:

    • 用这个方法可以给正数加上“+”前缀吗? +1.55 为 1.55
    猜你喜欢
    • 2011-03-27
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多