How to remove leading “0.” in a numeric R variable

2020-01-31 23:49发布

问题:

How can one concisely change a numeric R variable (keeping it numeric) so that, e.g., "-0.34" becomes simply "-.34"?

回答1:

Only when you output a numeric value do you have to choose a concrete representation (i.e., how the number should be formatted). You cannot change a numeric variable from "-0.34" to "-.34"; both are representations for the same number.

However, when you output an expression e, you can choose how it should be formatted. I don't know of any build-in way to leave off the leading "0", but you could always just remove it manually:

> sub("^(-?)0.", "\\1.", sprintf("%.2f", -0.34))
[1] "-.34"

You can define a function for convenience, e.g.,

numformat <- function(val) { sub("^(-?)0.", "\\1.", sprintf("%.2f", val)) }


回答2:

In addition to the existing answers, I wanted to mention that the package weights has a function rd() which can be used to "round numbers to text with no leading zero". Of course, the result is not numeric but character.

library("weights")
rd(-0.341, digits=2)
[1] "-.34"


回答3:

In addition to @stefan's nice answer, I stumbled upon the following code which accomplishes the same thing but prints out more decimal places:

f = function(X1)gsub("0\\.","\\.", X1)


回答4:

I needed to show numbers to 3 decimal places. If you want to print to an arbitrary number of decimal places and you don't want to have to add another package (i.e., the weights package above), then this function (adapted from @stefan's answer) seems to work:

numformat <- function(x, digits = 2) { 
    ncode <- paste0("%.", digits, "f")
    sub("^(-?)0.", "\\1.", sprintf(ncode, x))
}

So for example:

> numformat(-.232, 2)
[1] "-.23"
> numformat(-.232, 3)
[1] "-.232"
> numformat(-.232, 4)
[1] "-.2320"


回答5:

If it's for reporting in R Markdown I use the package MOTE with the function apa() and code: apa(-0.34, 2, FALSE) this will return -.34 in my documents.