Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading "0." in a numeric R variable

Tags:

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

like image 267
rolando2 Avatar asked Sep 28 '12 15:09

rolando2


People also ask

How do you get rid of leading zeros in integers?

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.


Video Answer


4 Answers

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)) }
like image 52
stefan Avatar answered Oct 12 '22 03:10

stefan


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"
like image 25
hplieninger Avatar answered Oct 12 '22 02:10

hplieninger


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"
like image 25
Jeromy Anglim Avatar answered Oct 12 '22 03:10

Jeromy Anglim


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)
like image 41
rolando2 Avatar answered Oct 12 '22 04:10

rolando2