Skip to content

Instantly share code, notes, and snippets.

@reinholdsson
Last active December 27, 2015 04:59
Show Gist options
  • Save reinholdsson/7271120 to your computer and use it in GitHub Desktop.
Save reinholdsson/7271120 to your computer and use it in GitHub Desktop.
R ReferenceClasses: dynamically create methods and overload tab autocomplete
# Variables to loop
vars <- c("var1", "var2")
# Generate a list of functions (specific for each variable)
var_methods <- lapply(vars, function(i){
fun <- function(var = i) paste("This is", var)
formals(fun)$var <- i
return(fun)
})
names(var_methods) <- vars
# Define new class
myClass <- setRefClass("myClass", methods = var_methods)
# Overload dollarnames
.DollarNames.myClass <- function(x, pattern) vars
a <- myClass()
# > a$
# tab shows: a$var1 a$var2
#
# > a$var2()
# [1] "This is var2"
@reinholdsson
Copy link
Author

# Define parent class
setRefClass(
  "Coldbir",
  methods = list(
    show = function() {
      print("Coldbir Database")
    }
  )
)

cdbTest <- function(path, vars) {
  # Generate a list of functions (specific for each variable)
  var_methods <- lapply(vars, function(i){
    fun <- function(var = i) paste("This is", var)
    formals(fun)$var <- i
    return(fun)
  })
  names(var_methods) <- vars

  # Return class object
  mclass <- setRefClass(
    Class = paste0("cdb<", path, ">"),
    contains = "Coldbir",
    fields = list(
      vars = "character"
    ),
    methods = list(
      initialize = function(vars) {
        vars <<- vars
      }
    )
  )

  mclass$methods(var_methods)
  mclass$new(vars)
}

# Overload dollar names
.DollarNames.Coldbir <- function(x, pattern){
  grep(pattern, x$vars, value = TRUE)   
}

a <- cdbTest("C:/path 1", c("var1", "var2"))
b <- cdbTest("C:/path 2", c("hej", "tjo"))

@reinholdsson
Copy link
Author

How about extending dollarnames with complete function calls?

.DollarNames.Coldbir <- function(x, pattern){
  grep(pattern, paste0("vars$", x$vars, "(2012)"), value = TRUE)    
}

Which means that we could also store all variable functions in field list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment