I would like to assign a function's contents as text to a variable, so that I can look for various patterns in it. (Actually, I'd like to assign every function's contents to look for how often each function is called from other functions, but that's easy to do once I can do it for one function).
At first glance, this seemed easy. That's why typing a function name in the console does, which means that print.function should show me how to do it:
> print.function
function (x, useSource = TRUE, ...)
.Internal(print.function(x, useSource, ...))
<environment: namespace:base>
Fail. So what if I just assigned the function contents to a variable and coerced them to character?
fxn_names <- apropos(".+")
fxns <- lapply(fxn_names,get)
as.character(fxns[[1]])
Error in as.character(fxns[[1]]) :
cannot coerce type 'builtin' to vector of type 'character'
Is there a trick here? Perhaps an .Internal function that I don't know about?
deparse?
> deparse(mean)
[1] "function (x, ...) " "UseMethod(\"mean\")"
> deparse(`+`)
[1] ".Primitive(\"+\")"
and as for getting all function as text, some tricks is necessary:
fxn_names <- apropos(".+")
fxns<-lapply(fxn_names,
function(f) eval(parse(text=paste("deparse(`", f, "`)", sep=""))))
UPDATED
here is more simple solution (thanks to @gsk3)
fxn_names <- apropos(".+")
fxns <- lapply(fxn_names, function(x)deparse(get(x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With