Reputation: 331
I can get obj_name list from the environment, but how to get obj_name from a .r file?
I tried ls but is only get obj_name from the environment, but I need get from R file, eg:
# filename test.R
func_1=function(){...}
func_2=function(){...}
func_3=function(){...}
c_1=R6Class()
#page end
I want to get test.R
's obj list name.
Like this:
"func_1","func_2","func_3","c_1"
Upvotes: 4
Views: 214
Reputation: 331
thanks for @PoGibas's solution. that's what i want
my_env=new.env()
source("myfile.R",local=my_env)
ls(my_env)
Upvotes: 2
Reputation: 132706
Sounds like an xy-problem. Anyway, you can parse the file and extract the first arguments of top-level calls to <-
and =
:
na.omit(
sapply(
as.list(
parse(text =
"# filename test.R
func_1=function(){...}
func_2=function(){...}
func_3=function(){...}
c_1=R6Class()
#page end")),
function(x) if (as.character(x[[1]]) %in% c("<-", "=")) as.character(x[[2]]) else NA))
#[1] "func_1" "func_2" "func_3" "c_1"
I'm assuming you don't use assign
or more exotic forms of assignment. If you need assignments nested in other functions (such as if
or for
), you'll need to write a recursive function that crawls the parse tree.
Upvotes: 4