How do I resolve "cannot add bindings to a locked environment" when working with setRefClass in R
0
0
Entering edit mode
@d1186cb1
Last seen 4.0 years ago
United States

I have a function in R as follows

DrawDistroGenerationClass <- function(in_hourStr, in_data){

  me <- methods::setRefClass(
    ## Define the environment where this list is defined so
    ## that I can refer to it later.
    "Draw",
    fields = list(hourStr = "character",
                  data = "numeric"),

    methods = list(
      getModel = function(){
        return("Draw Distro")
    },
      getName = function(){
        return(hourStr)
    },
      #' 
      #' @param strName the data to be drawn from
      #' @return the new hours value
      generateHoursFromStorage = function(strName){


        indSelect <- stats::runif(1, min = 1, max = length(data))

        componentLife <- data[indSelect]

        return(componentLife)
    }
    )
  )
  ## Set the name for the class
  newMe <- me$new(hourStr = in_hourStr, data = in_data)
  return(newMe)
}

The test looks like...

test_that("test Time2Repair-DrawDistroHoursGenerationClass", {

  distroHoursGenerationClass <- DrawDistroHoursGenerationClass("test", c(0.0, 1.0, 2.0, 3.0))


  testthat::expect_equal(distroHoursGenerationClass$getModel(), "Draw Distro")

  testthat::expect_equal(distroHoursGenerationClass$getName(), "test")

  testthat::expect_true(is.numeric(distroHoursGenerationClass$generateHoursFromStorage("test")))

}
)

With the purpose being I can call the function DrawDistroGenerationClass with a label and a set of values, and generate a function that will randomly draw from that set any time a call it.

The function works, but within my R project I have a unit test (testthat) for this function, and when I run R cmd I get:

  1. -methods::setRefClass(...)
  2. -methods::setClass(...)
  3. -methods::assignClassDef(Class, classDef, where)
  4. -base::assign(mname, def, where)

    "Error in assign(mname, def, where): cannot add bindings to a locked environment".

I have no idea why this problem is occurring/

I rather not make my input variables global (as they might conflict with other classes), and I'm using the setRefClass method here so I can make many independent versions of this function.

CMD setRefClass • 1.1k views
ADD COMMENT

Login before adding your answer.

Traffic: 1003 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6