Redefining a function in an R package

流过昼夜 提交于 2019-12-04 11:48:16

问题


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)


回答1:


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)...



来源:https://stackoverflow.com/questions/16317706/redefining-a-function-in-an-r-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!