Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does as.integer in R decrement the value?

Tags:

r

I am doing a simple operation of multiplying a decimal number and converting it to integer but the result seems to be different than expected. Apologies if this is discussed else where, I am not able to find any straight forward answers to this

> as.integer(1190.60 * 100)
[1] 119059

EDIT: So, I have to convert that to character and then do as.integer to get what is expected

> temp <- 1190.60
> temp2 <- 1190.60 * 100
> class(temp)
[1] "numeric"
> class(temp2)
[1] "numeric"
> as.character(temp2)
[1] "119060"
> as.integer(temp2)
[1] 119059
> as.integer(as.character(temp2))
[1] 119060

EDIT2: According to the comments, thanks @andrey-shabalin

> temp2
[1] 119060
> as.integer(temp2)
[1] 119059
> as.integer(round(temp2))
[1] 119060

EDIT3: As mentioned in the comments the question is related to behaviour of as.integer and not about floating calculations

like image 222
pshirishreddy Avatar asked Apr 19 '17 13:04

pshirishreddy


People also ask

How does as integer round in R?

You can use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits.

How to declare a variable as integer in R?

To assign a variable with an integer value in R programming, call as. integer() function, and pass the numeric value to this function. as. integer(x) returns an integer value of x.

How to set an integer in R?

Integer Datatype R supports integer data types which are the set of all integers. You can create as well as convert a value into an integer type using the as. integer() function. You can also use the capital 'L' notation as a suffix to denote that a particular value is of the integer data type.


1 Answers

The answer to this is "floating point error". You can see this easily by checking the following:

> temp <- 1190.60
> temp2 <- 1190.60 * 100
> temp2 - 119060
[1] -1.455192e-11

Due to floating point errors, temp2 isn't exactly 119060 but :

> sprintf("%.20f", temp2)
[1] "119059.99999999998544808477"

If you use as.integer on a float, it works the same way as trunc, i.e. it does round the float in the direction of 0. So in this case that becomes 119059.

If you convert to character using as.character(), R will make sure that it uses maximum 15 significant digits. In this example that would be "119059.999999999". The next digit is another 9, so R will round this to 119060 before conversion. I avoid this in the code above by using sprintf() instead of as.character().

like image 135
Joris Meys Avatar answered Sep 20 '22 18:09

Joris Meys