3

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??

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Green44
  • 53
  • 3

4 Answers4

3

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).

Community
  • 1
  • 1
milan
  • 4,782
  • 2
  • 21
  • 39
2

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
Miha
  • 2,559
  • 2
  • 19
  • 34
  • @Richard Scriven good point, unfortunately I've made a mistake which I corrected (see my edit in a post). – Miha Jun 18 '16 at 07:23
  • Your solution heavily relies on `options("scipen"=100, "digits"=10)`. One should change R default options to use it. – 989 Jun 19 '16 at 14:27
1

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.

989
  • 12,579
  • 5
  • 31
  • 53
0
>  as.numeric(gsub("^[0.]*", "", paste(0.000278)))
[1] 278
Marcelo Ventura
  • 581
  • 7
  • 19