2

I have a column of numeric class, e.g.: v <- c(12345, 2345, 7689900).

I know that every number is actually of the form 12.345, 23.45, 76.89900, ie every numeric has two digits and the rest is decimals.

How can I convert the vector to this format? No decimal should be cropped in the process.

zx8754
  • 52,746
  • 12
  • 114
  • 209
spore234
  • 3,550
  • 6
  • 50
  • 76

3 Answers3

2

If you are looking for a numeric vector, one option could be:

v/10^(nchar(v) - 2)

[1] 12.345 23.450 76.899

Edit:

In cases when we have more than 20 digits, we can Count the number of integer digits using log10:

v/10^(floor(log10(abs(v))) + 1 - 2)
zx8754
  • 52,746
  • 12
  • 114
  • 209
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
1

Using regex we can capture the data in two groups separated by ".".

sub('(..)(.*)', '\\1.\\2', v)
#[1] "12.345"   "23.45"    "76.89900"

You can wrap this in as.numeric if you want to perform some manipulation on this.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1
as.numeric(paste0(substring(v,1,2), ".", substring(v,3)))
# [1] 12.345 23.450 76.899
s_baldur
  • 29,441
  • 4
  • 36
  • 69