Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

safest way to assign an integer (worried about truncation)

I really just want to do something like

x <- as.integer(c(1,2,3))

But because c(1,2,3) is stored as a floating point vector I'm worried that I'll have problems with truncation, such as

> as.integer(1.99999999999)
[1] 1

How do I know I'm safe?

like image 650
Xu Wang Avatar asked Dec 28 '22 03:12

Xu Wang


1 Answers

you can use a suffix L:

> x <- c(1L, 2L, 3L)
> is.integer(x)
[1] TRUE

> x <- 1L:3L
> x
[1] 1 2 3
> is.integer(x)
[1] TRUE

Or if you already have a numeric vector and convert it into integer, you can explicitly describe the rule:

> x <- c(-0.01, 1.999, 2, 3.000001)
> as.integer(round(x))
[1] 0 2 2 3
> as.integer(floor(x))
[1] -1  1  2  3
> as.integer(trunc(x))
[1] 0 1 2 3
> as.integer(ceiling(x))
[1] 0 2 2 4
like image 71
kohske Avatar answered Jan 08 '23 08:01

kohske