The 'sparcl' package uses the 'kmeans' function in the standard 'stat' package. I want to make it use my own implementation of kmeans++ instead.
One way to do this would be to edit the code in the sparcl package itself. I'd prefer to avoid this, both because it would be messy and because I'm not sure how I would then install that edited code in R.
Unfortunately, the superassignment operator "<<-" doesn't work:
> kmeans <<- function(x) print("hi!")
Error: cannot change value of locked binding for 'kmeans'
neither does "assign":
assign("kmeans",function(x) {print("HI THERE!"); return(FALSE)},pos="package:sparcl")
Error in assign("is.null", function(x) { :
cannot add bindings to a locked environment
So is editing the package code the only way?
Thanks!
If you do want to edit a function's body (but not its arguments) during an interactive session, you can use
trace()
, like this:Then, in the editor that pops up, edit the body, so that it looks like this (for example):
Save the edited function definition and then exit the editor.
Back at the R command line, you can view the edited function and try it out:
Finally, to revert to the unedited function, just do
untrace("kmeans")
. (I generally prefer usingtrace()
toassignInNamespace()
and friends becauseuntrace()
makes it so easy to undo changes.)On further thought (and after re-reading your question), here's a simple solution that should work for you.
All you need to do is to assign your edited version of
kmeans()
to the symbolkmeans
in the global environment. In other words, at the command line do this:This works because
KMeansSparseCluster()
(and calls to any other functions inpackage:sparcl
) look forkmeans
first innamespace:sparcl
, then inimports:sparcl
, then innamespace:base
, and then in.GlobalEnv
, where it'll find your redefinedkmeans
before it gets to the one inpackage:stats
. To have a look yourself, try this:Nicely, functions from the stats package that use
kmeans()
won't be disrupted by your version, because they will findkmeans
in their own namespace, before the symbol-search ever gets to the global environment.