Green44
Green44

Reputation: 53

Remove all leading zeros and turn number into a positive

I'm trying to convert .000278 into 278 in R but all functions I see can only move it to .278. It needs to be a whole, positive number.

Is there a function that will remove the .0+ preceding a number??

Upvotes: 3

Views: 242

Answers (4)

milan
milan

Reputation: 5000

I assume you want to apply this to many numbers at once (otherwise I might not understand the question).

a <- c(0.003, 0.0056, 0.000278)#Example data
a*(10^(nchar(a)-2))
[1]   3  56 278

Make sure scientific notation is disabled with scipen, as discussed in this post (e.g., by doing options(scipen=999). This is important because nchar counts the number of characters the numbers have (minus 2 for "0.").

Another approach. Use the package stringr.

a <- c(0.003, 0.0056, 0.000278)#Example data
library(stringr)
as.numeric(str_replace(a, "0.", ""))
[1]   3  56 278

Note that with this method you need to convert the output of str_replace back to numeric using as.numeric (not ideal).

Upvotes: 3

Miha
Miha

Reputation: 2884

Or use

substr and regexpr what gives exactly what you wanted

x <- 0.000278
as.numeric(substr(x ,regexpr("[^0.]",x),nchar(x)))
[1] 278

And this also works for different numbers, just set:

options("scipen"=100, "digits"=10) # Force R not to use exponential notation (e.g. e-8)

and you could try for example:

z <- 0.000000588
as.numeric(substr(z ,regexpr("[^0.]",z),nchar(z)))
[1] 588

Upvotes: 2

Marcelo Ventura
Marcelo Ventura

Reputation: 599

>  as.numeric(gsub("^[0.]*", "", paste(0.000278)))
[1] 278

Upvotes: 0

989
989

Reputation: 12935

Try this (len is adjustable):

a <- 0.000278
a*(10^match(T,round(a, 1:(len=10)) == a)) # counts the number of decimals places
# 278

Use as.numeric(a) in case a is of type character.

Upvotes: 1

Related Questions