How to generate auto-incrementing ID in R

后端 未结 2 439
一整个雨季
一整个雨季 2020-12-29 11:42

I am looking for an efficient way to create unique, numeric IDs for some synthetic data I\'m generating.

Right now, I simply have a function that emits and incremen

2条回答
  •  忘掉有多难
    2020-12-29 11:54

    I like to use the proto package for small OO programming. Under the hood, it uses environments in a similar fashion to what Martin Morgan illustrated.

    # 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"
    

提交回复
热议问题