How can I load an object into a variable name that I specify from an R data file?

前端 未结 7 2171
你的背包
你的背包 2020-11-28 19:50

When you save a variable in an R data file using save, it is saved under whatever name it had in the session that saved it. When I later go to load it from anot

7条回答
  •  悲哀的现实
    2020-11-28 20:35

    In case anyone is looking to do this with a plain source file, rather than a saved Rdata/RDS/Rda file, the solution is very similar to the one provided by @Hong Ooi

    load_obj <- function(fileName) {
    
      local_env = new.env()
      source(file = fileName, local = local_env)
    
      return(local_env[[names(local_env)[1]]])
    
    }
    
    my_loaded_obj = load_obj(fileName = "TestSourceFile.R")
    
    my_loaded_obj(7)
    

    Prints:

    [1] "Value of arg is 7"

    And in the separate source file TestSourceFile.R

    myTestFunction = function(arg) {
      print(paste0("Value of arg is ", arg))
    }
    

    Again, this solution only works if there is exactly one file, if there are more, then it will just return one of them (probably the first, but that is not guaranteed).

提交回复
热议问题