4

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"
pogibas
  • 27,303
  • 19
  • 84
  • 117
SummersKing
  • 301
  • 1
  • 11
  • 1
    Good question, you can `source` `.R` file to a new environment and get object names from there - https://stackoverflow.com/questions/39620669/source-script-to-separate-environment-in-r-not-the-global-environment – pogibas Dec 09 '19 at 08:46
  • @PoGibas I guess OP wants to retrieve the objects without sourcing the file – ThomasIsCoding Dec 09 '19 at 08:57
  • thanks a lot , your answer slove my question briefly! – SummersKing Dec 09 '19 at 09:44

2 Answers2

4

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.

Roland
  • 127,288
  • 10
  • 191
  • 288
2

thanks for @PoGibas's solution. that's what i want

my_env=new.env()
source("myfile.R",local=my_env)
ls(my_env)
SummersKing
  • 301
  • 1
  • 11