user1769197
user1769197

Reputation: 2213

How do you cast a double to an integer in 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 ??

Upvotes: 19

Views: 87752

Answers (4)

IRTFM
IRTFM

Reputation: 263451

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. However, you can change that level. 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.

The function is.integer can be used to test for integer mode.

is.integer(3)
[1] FALSE
is.integer(3L)
[1] TRUE

Neither round nor trunc will return a vector in integer mode:

is.integer(trunc(3.4))
[1] FALSE

Upvotes: 13

kakarot
kakarot

Reputation: 438

If you have a numeric matrix you wish to coerce to an integer matrix (e.g., you are creating a set of dummy variables from a factor), as.integer(matrix_object) will coerce the matrix to a vector, which is not what you want. Instead, you can use storage.mode(matrix_object) <- "integer" to maintain the matrix form.

Upvotes: 4

emanuele
emanuele

Reputation: 2589

The function as.integer() truncate the number up to 0 order, so you must add a 0.5 to get a proper approx

dd<-64.00000000
as.integer(dd+0.5)

Upvotes: 6

flodel
flodel

Reputation: 89097

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).

Upvotes: 8

Related Questions