Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast a double to an integer in R?

Tags:

r

My question is: Suppose you have computed an algorithm that gives the number of iterations and you would like to print the number of iterations out. But the output always many decimal places, like the following:

64.00000000

Is it possible to get an integer by doing type casting in R ? How would you do it ??

like image 267
user1769197 Avatar asked Nov 03 '12 00:11

user1769197


People also ask

Can you cast a double to an integer?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.

How do I convert a variable to an integer in R?

To convert String to Integer in R programming, call strtoi() function, pass the string and base values to this function. strtoi(string, base) returns the integer value of the given string with respect to the specified base.

What is the correct syntax for casting from double to int?

Using Math. Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.


2 Answers

Instead of trying to convert the output into an integer, find out why it is not an integer in the first place, and fix it there.

Did you initialize it as an integer, e.g. num.iterations <- 0L or num.iterations <- integer(1) or did you make the mistake of setting it to 0 (a numeric)?

When you incremented it, did you add 1 (a numeric) or 1L (an integer)?

If you are not sure, go through your code and check your variable's type using the class function.

Fixing the problem at the root could save you a lot of trouble down the line. It could also make your code more efficient as numerous operations are faster on integers than numerics (an example).

like image 38
flodel Avatar answered Oct 02 '22 12:10

flodel


There are some gotchas in coercing to integer mode. Presumably you have a variety of numbers in some structure. If you are working with a matrix, then the print routine will display all the numbers at the same precision. If you have calculated this result with an arithmetic process it may be actually less than 64 bit display as that value.

> 64.00000000-.00000099999
[1] 64
> 64.00000000-.0000099999
[1] 63.99999

So assuming you want all the values in whatever structure this is part of, to be displayed as integers, the safest would be:

round(64.000000, 0)

... since this could happen, otherwise.

> as.integer(64.00000000-.00000000009)
[1] 63

The other gotcha is that the range of value for integers is considerably less than the range of floating point numbers.

like image 199
IRTFM Avatar answered Oct 02 '22 14:10

IRTFM