【问题标题】:What is the difference between trunc() and as.integer()?trunc() 和 as.integer() 有什么区别?
【发布时间】:2017-05-10 13:35:00
【问题描述】:

trunc()as.integer() 有什么区别?

为什么as.integer 更快?谁能解释一下幕后发生了什么?

为什么trunc() 返回类double 而不是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 接受单个数字参数 x 并返回一个数字向量,其中包含通过将 x 中的值向 0 截断而形成的整数。"

help(as.integer)

“非整数数值被截断为零(即,as.integer(x) 在那里等于 trunc(x)),[...]”

背景:我正在编写函数以在不同的时间/日期表示之间进行转换,例如 120403 (hhmmss) -&gt; 43443(自 00:00:00 以来的秒数)性能才是最重要的。

注意:本题与浮点运算无关

SessionInfo: R version 3.3.2, Windows 7 x64

【问题讨论】:

  • 如果您将 r 用于整数截断方法的性能差异很重要的应用程序,请重新考虑将 r 用于该应用程序
  • 好点。我看到对于 R 基础,这个问题没有多大意义。我忘了提到我正在使用 data.table。但你还是对的,trunc() 不会成为瓶颈。

标签: r performance integer truncate


【解决方案1】:

在技术方面,这些功能有不同的目标。

trunc 函数删除数字的小数部分。

as.integer 函数将输入值转换为 32 位整数。

因此as.integer 会溢出大数字(超过 2^31):

x = 9876543210.5

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

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

as.integer(x)
# [1] NA

【讨论】:

  • 我明白了,谢谢。整数溢出可能是 R 坚持双打的原因之一。 {bit64} 可能是一种解决方法。我想要整数,因为它们成为在 data.table 中键入的行 ID。在 R 基础中,我们通常不关心整数/数字(参见例如 Burns 的 R-Inferno),我们甚至可以按小数对行进行子集化。但是使用 data.table 我开始区分。
【解决方案2】:

vector 中的值已经是 numeric

as.integer用于将数据转换为numeric

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

【讨论】:

  • 这里的问题是你在参数周围有引号。 R 将 "3.55" 解释为长度为 1 的字符向量(即文本字符串)。 as.integer 函数很乐意强制字符对象输入整数(这是它的设计目的之一),但 trunc 需要一个数字参数。 trunc(3.55) 返回3(类型为"double")。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2011-12-12
  • 2010-09-16
  • 2012-03-14
相关资源
最近更新 更多