【问题标题】:Add a dot after a number in R在R中的数字后添加一个点
【发布时间】:2017-11-15 13:22:20
【问题描述】:

我有以下列表 c(1.23,1,0.9) 显示在控制台[1] 1.23 1 0.9 中,我想将其转换为: [1] 1.23,1.,.9 。 如您所见,第一个数字保持不变,但 1 变为 1。而 0.9 变为 .9。

有没有一种优雅的方式来获得这种格式?

问候

【问题讨论】:

    标签: r format decimal


    【解决方案1】:

    这是印刷或表示的问题。

    您可能想要做的是将其转换为一个字符:

    res <- as.character(c(1.23,1,0.9))
    

    然后使用正则表达式:

    res <- gsub("^0", "", res) # delete leading 0s
    res[!grepl("\\.", res)] <- paste0(res[!grepl("\\.", res)], ".") # Add a "." at the end where there are no 0s
    

    结果是:

    res
    [1] "1.23" "1."   ".9" 
    

    【讨论】:

    • 他可以创建一个 S3 类并将这种方法用于打印方法。然后他可以在print.default 中设置quote = FALSE,从而避免引号。
    【解决方案2】:

    这是一个带有sprintfgsub的方法:

    gsub("0", "", sprintf("%.2f", x))
    [1] "1.23" "1."   ".9"
    

    要添加逗号,您可以将其放在 paste 函数中。

    paste(gsub("0", "", sprintf("%.2f", x)), collapse=",")
    [1] "1.23,1.,.9"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2022-09-24
      相关资源
      最近更新 更多