Reputation: 4532
I occasionally run into functions with restrictive arguments. These community contributed functions can be absolutely great otherwise and I would like to be able to define a new function changing just the behavior bothering me, on the fly (without having to rewrite the whole function into a script file).
I know how to visualize a function in R, just type the name of the function. But how to save, modify and define a new function with the modified definition.
Upvotes: 3
Views: 429
Reputation: 4532
It recently happened to me, answering this question.
Of course this is not meant to be rock solid coding but just a way to do quickly what you want when you need it (thanks to the commenter pointing it out). In case of issues check the last part in this post.
The initial vis.gam
function defined a palette of gray from 0.1 to 0.9 and I wanted it to go from 0.9 to 0.1.
A quick check of the function shows that there is no easy way to provide a palette but it's easy to change the problematic line:
[156] " pal <- gray(seq(0.1, 0.9, length = nCol))"
It is actually really easy and concise to change such a line:
# first save the definition as a list of string
newDef <- deparse(vis.gam)
# then identify the line to be changed using regular expressions
# (see ?regexp)
iLine <- grep("gray\\(seq\\(",initDef)
# replace the line by what you want
newDef[iLine] <- " pal <- gray(seq(0.9, 0.1, length = nCol))"
# and define a new function by parsing and evaluating the
# new definition
vis.gam2 <- eval(parse(text=newDef))
Done
The new function might complain when running about missing functions. This is due to package namespace issues. It means the function is calling functions internal to the package that are not available in the general namespace. You need then to specify the package replacing
functionName
by packageName:::functionName
in the definition, for example using gsub
.
Upvotes: 3