3

We have seen many questions regarding How to save the decimal places while converting factors to numbers such as this and this. But I did not see anything that do the same with character data instead of factor data. Below is what I tried without success:

f1 <- c("402313.01399128098", "402896.30908451998", "403165.63827027398", "403169.06116369402", "402891.96329268801", "402239.74412469601", 
        "402271.54950727499", "402313.01399128098")
as.numeric(as.character(f1)) # does not work

f2 <- as.factor(f1) 
as.numeric(as.character(f2)) # my decimals are GONE

f3 <- levels(f2) 
as.numeric(f3) # my decimals are gone again

I get this

[1] 402239.7 402271.5 402313.0 402892.0 402896.3 403165.6 403169.1

Update after the answer/comments:

There was no loss of decimal places. But I do not know why it was not showing. With options(digits = 15) I could see all the decimals.

Lesson: You may run options() before you decide to ask such questions.

Community
  • 1
  • 1
Stat-R
  • 5,040
  • 8
  • 42
  • 68
  • 1
    I don't think you're losing anything. You're only seeing the values represented with a different number of decimal places. – Benjamin Oct 20 '15 at 15:16
  • 1
    @Minnow, the R inferno (which I love) talks about finite-precision representation of numbers, but it doesn't talk (as much) about the difference between internal structure and external representation ... – Ben Bolker Oct 20 '15 at 15:38

1 Answers1

5

All of the digits are still there. That is just the default printing method.

new.vec <- as.numeric(f1)
print(new.vec, digits=20)
#[1] 402313.01399128098 402896.30908451998 403165.63827027398
#[4] 403169.06116369402 402891.96329268801 402239.74412469601
#[7] 402271.54950727499 402313.01399128098

You can also change the default with options(digits = n).

More information here.

Community
  • 1
  • 1
Pierre L
  • 28,203
  • 6
  • 47
  • 69