How can one concisely change a numeric R variable (keeping it numeric) so that, e.g., "-0.34" becomes simply "-.34"?
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
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)) }
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"
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"
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With