我真的只想做点什么
x <- as.integer(c(1,2,3))
Run Code Online (Sandbox Code Playgroud)
但因为c(1,2,3)存储为浮点向量,我担心我会遇到截断问题,比如
> as.integer(1.99999999999)
[1] 1
Run Code Online (Sandbox Code Playgroud)
我怎么知道我很安全?
koh*_*ske 10
你可以使用后缀L:
> x <- c(1L, 2L, 3L)
> is.integer(x)
[1] TRUE
> x <- 1L:3L
> x
[1] 1 2 3
> is.integer(x)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
或者,如果您已有数字向量并将其转换为整数,则可以明确描述该规则:
> 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
Run Code Online (Sandbox Code Playgroud)