Skip to content
Prev 181356 / 398502 Next

how to implement a circular buffer with R

milton ruser wrote:
not sure if this is what you want, but it might provide a hint:


    circularize = function(string) {
       name = deparse(substitute(string))
       index = 0
       length = nchar(string)
       rm(list=name, envir=parent.frame())
       makeActiveBinding(
          name,
          function(value, ...)
             if (missing(value)) {
                index <<- index %% length + 1
                if (index == 1) string
                else paste(
                    substr(string, index, length),
                    substr(string, 1, index-1),
                    sep='') }
             else
                stop(sprintf('cannot assign to circularized string
"%s"', name)),
          parent.frame()) }

    string = 'foo'
    circularize(string)

    string
    # "foo"
    string
    # "oof"
    string
    # "ofo"
    string
    # "foo"
    # ...