What is the difference between trunc () and as.integer ()?

What is the difference between trunc()

and as.integer()

?

Why as.integer

faster? Can someone please explain what's going on behind the curtain?

Why does it trunc()

return a class double

instead integer

?

x <- c(-3.2, -1.8, 2.3, 1.5, 1.500000001, -1.499999999)

trunc(x)
[1] -3 -1  2  1  1 -1

as.integer(x)
[1] -3 -1  2  1  1 -1

all.equal(trunc(x), as.integer(x))
[1] TRUE

sapply(list(trunc(x), as.integer(x)), typeof)
[1] "double" "integer"

library(microbenchmark)
x <- sample(seq(-5, 5, by = 0.001), size = 1e4, replace = TRUE)
microbenchmark(floor(x), trunc(x), as.integer(x), times = 1e4)
# I included floor() as well just to see the performance difference

Unit: microseconds
          expr    min     lq      mean median     uq       max neval
      floor(x) 96.185 97.651 126.02124 98.237 99.411 67892.004 10000
      trunc(x) 56.596 57.476  71.33856 57.770 58.649  2704.607 10000
 as.integer(x) 16.422 16.715  23.26488 17.009 18.475  2828.064 10000

      

help(trunc)

:

"trunc takes one numeric argument, x, and returns a numeric vector containing integers formed by truncating the x values ​​in the 0 direction.

help(as.integer)

:

"Non-integer numeric values ​​are truncated to zero (ie as.integer (x) is equal to trunc (x)), [...]"

Background . I am writing functions to translate between different time and date representations, for example 120403 (hhmmss) -> 43443

(seconds from 00:00:00). Efficiency is all that matters.

Note: this question has nothing to do with floating point arithmetic

SessionInfo: R version 3.3.2, Windows 7 x64

      

+3


source to share


2 answers


From a technical point of view, these functions have different purposes.

The function trunc

removes the fractional part of numbers.

The function as.integer

converts input values ​​to 32-bit integers.



Thus, as.integer

will overflow by large numbers (over 2 ^ 31):

x = 9876543210.5

sprintf("%15f", x)
# [1] "9876543210.500000"

sprintf("%15f", trunc(x))
# [1] "9876543210.000000"

as.integer(x)
# [1] NA

      

+4


source


The values ​​are vector

already in numeric

.

as.integer

used to convert data to numeric

:



as.integer("3.55")
# [1] 3
trunc("3.55")
# Error in trunc("3.55") : non-numeric argument to mathematical function

      

0


source







All Articles