Skip to content

Instantly share code, notes, and snippets.

@rpietro
Created September 6, 2013 23:49
Show Gist options
  • Save rpietro/6471450 to your computer and use it in GitHub Desktop.
Save rpietro/6471450 to your computer and use it in GitHub Desktop.
metaprogramming example from http://goo.gl/fmIh4T
# script from http://goo.gl/fmIh4T
myFun <- function(vec) {
numElements <- length(which(vec > threshold))
numElements
}
genMyFuns <- function(thresholds) {
ll <- length(thresholds)
print("Generating functions:")
for(i in 1:ll) {
fName <- paste("myFun.", i, sep="")
print(fName)
assign(fName, eval(
substitute(
function(vec) {
numElements <- length(which(vec > tt));
numElements;
},
list(tt=thresholds[i])
)
),
envir=parent.frame()
)
}
}
genMyFuns(c(7, 9, 10))
myFun.1(1:20)
myFun.2(1:20)
myFun.3(1:20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment