在R中的数字后面添加一个点

Pro*_*Tyu 0 format r decimal

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

有这种格式的优雅方式吗?

问候

Emm*_*Lin 5

这是打印或表示的问题.

您可能想要做的是将其转换为角色:

res <- as.character(c(1.23,1,0.9))
Run Code Online (Sandbox Code Playgroud)

然后使用regexp:

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

结果是:

res
[1] "1.23" "1."   ".9" 
Run Code Online (Sandbox Code Playgroud)