Learn R Programming

xfun (version 0.50)

find_globals: Find global/local variables in R code

Description

Use codetools::findGlobals() and codetools::findLocalsList() to find global and local variables in a piece of code. Global variables are defined outside the code, and local variables are created inside the code.

Usage

find_globals(code, envir = parent.frame())

find_locals(code)

Value

A character vector of the variable names. If the source code contains syntax errors, an empty character vector will be returned.

Arguments

code

Either a character vector of R source code, or an R expression.

envir

The global environment in which global variables are to be found.

Examples

Run this code
x = 2
xfun::find_globals("y = x + 1")
xfun::find_globals("y = get('x') + 1")  # x is not recognized
xfun::find_globals("y = zzz + 1")  # zzz doesn't exist

xfun::find_locals("y = x + 1")
xfun::find_locals("assign('y', x + 1)")  # it works
xfun::find_locals("assign('y', x + 1, new.env())")  # still smart
xfun::find_locals("eval(parse(text = 'y = x + 1'))")  # no way

Run the code above in your browser using DataLab