如何在R中生成自动递增ID

时间:2014-09-18 00:09:35

标签: r

我正在寻找一种有效的方法来为我生成的某些合成数据创建唯一的数字ID。

现在,我只是有一个函数可以从全局变量中发出并递增一个值(参见下面的演示代码)。但是,这很麻烦,因为我必须初始化idCounter变量,如果可能的话我宁愿不使用全局变量。

# Emit SSN
idCounter = 0
emitID = function(){
  # Turn into a formatted string
  id = formatC(idCounter,width=9,flag=0,format="d")

  # Increment id counter
  idCounter <<- idCounter+1

  return(id)
}
record$id = emitID()

uuid包提供了接近我想要的功能,但我需要ID才是整数。有什么建议?也许是一种将UUID值转换为某种数值的方法?显然会发生一些碰撞,但这可能是正常的。我认为,至多我需要10亿个价值。

感谢您的任何建议!

-Rob

2 个答案:

答案 0 :(得分:22)

计数器的非全局版本使用词法范围用增量函数封装idCounter

emitID <- local({
    idCounter <- -1L
    function(){
        idCounter <<- idCounter + 1L                     # increment
        formatC(idCounter, width=9, flag=0, format="d")  # format & return
    }
})

然后

> emitID()
[1] "000000000"
> emitID1()
[1] "000000001"
> idCounter <- 123   ## global variable, not locally scoped idCounter
> emitID()
[1] "000000002"

一个有趣的选择是使用“工厂”模式来创建独立的计数器。你的问题意味着你将这个函数称为十亿(嗯,不知道我的印象在哪里......)时间,所以也许通过创建一个id的缓冲区来向formatC的调用进行矢量化是有意义的吗?

idFactory <- function(buf_n=1000000) {
    curr <- 0L
    last <- -1L
    val <- NULL
    function() {
        if ((curr %% buf_n) == 0L) {
            val <<- formatC(last + seq_len(buf_n), width=9, flag=0, format="d")
            last <<- last + buf_n
            curr <<- 0L
        }
        val[curr <<- curr + 1L]
    }
}
emitID2 <- idFactory()

然后(emitID1是上面的局部变量版本的实例。)

> library(microbenchmark)
> microbenchmark(emitID1(), emitID2(), times=100000)
Unit: microseconds
      expr    min     lq median     uq      max neval
 emitID1() 66.363 70.614 72.310 73.603 13753.96 1e+05
 emitID2()  2.240  2.982  4.138  4.676 49593.03 1e+05
> emitID1()
[1] "000100000"
> emitID2()
[1] "000100000"

(原型解决方案比emitID1慢约3倍,但速度不是万能的。)

答案 1 :(得分:5)

我喜欢使用proto包进行小型OO编程。在引擎盖下,它使用的环境与Martin Morgan所说的类似。

# this defines your class
library(proto)
Counter <- proto(idCounter = 0L)
Counter$emitID <- function(self = .) {
   id <- formatC(self$idCounter, width = 9, flag = 0, format = "d")
   self$idCounter <- self$idCounter + 1L
   return(id)
}

# This creates an instance (or you can use `Counter` directly as a singleton)
mycounter <- Counter$proto()

# use it:
mycounter$emitID()
# [1] "000000000"
mycounter$emitID()
# [1] "000000001"
相关问题