Last active
December 27, 2015 04:59
-
-
Save reinholdsson/7271120 to your computer and use it in GitHub Desktop.
R ReferenceClasses: dynamically create methods and overload tab autocomplete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" |
Author
reinholdsson
commented
Nov 2, 2013
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