Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning function contents to a variable for text processing

Tags:

r

data-mining

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?

like image 209
Ari B. Friedman Avatar asked Dec 30 '25 11:12

Ari B. Friedman


1 Answers

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)))
like image 108
kohske Avatar answered Jan 02 '26 03:01

kohske