As.numeric () removes decimals in R, how to change?

I have, for what I hope, a simple question about as.numeric (). I have a bunch of data with numbers written as characters. I want them to be numeric, but as.numeric () removes the decimal spots. For instance:

y <- as.character("0.912345678") as.numeric(y) 0.9123457 

Thanks:)

+6
source share
2 answers

R basically does some basic configuration to print the number of digits required. You can change this with the digits option as follows:

 > options(digits=9) > y <- as.character("0.912345678") > as.numeric(y) [1] 0.912345678 

A small EDIT for clarity: digits matches the number of digits to display everything , not just the number of digits after the decimal point.

For instance,

 > options(digits=9) > y <- as.character("10.123456789") > as.numeric(y) [1] 10.1234568 

In your example, above the leading zero before the decimal point is not taken into account, so 9 digits were enough to display the full number.

+4
source

What happens is that R only displays fixed digits.

This R-help reports what is happening. To quote Peter Dalgaard, "There is a difference between an object and the display of an object."

In your example

 y2 = as.numeric(y) print(y2) # [1] 0.9123457 

but subtract 0.9 to see

 y2 - 0.9 # [1] 0.01234568 

Updated based on @Khashaa comment. To change the display, use

 options(digits = 9) y2 # [1] 0.912345678 
+4
source

Source: https://habr.com/ru/post/986001/


All Articles