I need to write a function to add a particular command/string of characters to an existing function.
Consider this function:
constraint = function(cov_matrix,max_variance){
function(x){
f = NULL
g = NULL
g = rbind(g, t(x)%*%cov_matrix%*%x-max_variance)
return(list(ceq = f, c= g))
}
}
Ideally, I would like to write a function add_text() that would take as input ("some_text_or_command", constraint) that would generate the output.
constraint = function(cov_matrix, max_variance){
function(x){
f = NULL
g = NULL
g = rbind(g, t(x)%*%cov_matrix%*%x- max_variance)
"some_text_or_command"
return(list(ceq = f, c= g))
}
}
How to go about it?
body()(2)formals()(3)parse()(4)as.call()(5)deparse()(6)eval(). You probably need to do something withgsub()orgrep()to inject your "command" on the desired line. All in all, this seems like a very strange thing, I suspect XY problem.eval, run and readfortunes::fortune(106).body(), and edit the parsed version of the function. But your question is incomplete: How isadd_text()supposed to figure out where to add the new code?