Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining a function in an R package

I tried to modify and redefine a function (xcmsRaw) in R package xcms by first defining a function

my.xcmsRaw <- function(filename, profstep = 1, profmethod = "bin",
                    profparam = list(mzcorrf=1),    # PATCH - mzcorrf is the m/z correction factor, e.g. 0.99888 for long-chain hydrocarbons
                    includeMSn = FALSE, mslevel=NULL,
                    scanrange=NULL) { ... }

and then typing

unlockBinding("xcmsRaw", as.environment("package:xcms"))
assign("xcmsRaw", my.xcmsRaw, as.environment("package:xcms"))
lockBinding("xcmsRaw", as.environment("package:xcms"))

However, when I run it it gives me the error

Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'profBinM' of mode 'function' was not found

caused by it not finding the profBinM function, which is a C code function defined in file xcms.c of the xcms package.

Any thoughts on how I could resolve this issue? (I am working under Windows 7, using R version 3.0.0)

like image 210
Tom Wenseleers Avatar asked May 01 '13 11:05

Tom Wenseleers


People also ask

Can you redefine a function?

No, it's not possible. This person is refering to this topic (most likely). He was struggling with the fact that he has to define a function for every class. You can redefine a function if you are doing inheritance.

Can you put a function inside a function in R?

In simpler words, a nested function is a function in another function. There are two ways to create a nested function in the R programming language: Calling a function within another function we created. Writing a function within another function.


1 Answers

Thanks Josh - in my case I got it working now via

modifline='if ((profparam$mzcorrf!=1)&length(unique(rawdata$mz - trunc(rawdata$mz)))!=1) {rawdata$mz=rawdata$mz*profparam$mzcorrf} else if (profparam$mzcorrf!=1) {print("Exact masses were already rounded to nominal masses");profparam$mzcorrf=1}'
insertatline=6
trace(xcmsRaw, tracer=modifline,at=c(insertatline))

where I found the correct line to insert my modified code using

as.list(body(xcmsRaw))

To suppress the output of trace I then defined a second function

xcmsRaw2=function(...) {sink("NUL");obj=xcmsRaw(...);sink();return(obj) }

which can the be called and which does not provide any unnecessary tracing output.

Would still be nice to get it working via assignInNamespace() too though, as that would allow for more extensive edits/redefinitions and also for changes in the function arguments (which would be a common reason to redefine functions, that is, to take some extra argument)...

like image 146
Tom Wenseleers Avatar answered Sep 28 '22 08:09

Tom Wenseleers