Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect free variable names in R functions [duplicate]

Tags:

r

Suppose I have a function:

f <- function() {
  x + 1
}

Here x is a free variable since its value is not defined within function f. Is there a way that I can obtain the variable name, say x, from a defined function, say f?

I am asking this question while maintaining others' old R codes. There are a lot of free variables used, and that makes debugging hard.

Any suggestions are welcomed as well.

like image 779
zhanxw Avatar asked Aug 18 '14 23:08

zhanxw


1 Answers

The codetools package has functions for this purpose, eg findGlobals

findGlobals(f, merge=FALSE)[['variables']]
# [1] "x"

if we redefine the function to have a named argument x then no variables are returned.

f2 <- function(x){
  x+1
}
findGlobals(f2, merge=FALSE)[['variables']]
# character(0)
like image 97
mnel Avatar answered Sep 17 '22 13:09

mnel