Source script to separate environment in R, not the global environment

后端 未结 5 1854
闹比i
闹比i 2020-12-08 22:24

Is there a way to source() a script in R such that it is attached as a parent to the global environment (.GlobalEnv)?

Curr

5条回答
  •  青春惊慌失措
    2020-12-08 22:36

    I'm not sure if my answer is any different from the answers given above, but I use the following code:

    if (!exists('.env')) .env <- new.env() # creates an environment in which to store functions
    if ('.env' %in% search()) detach(.env) # detaches .env if it already exists; does not "erase" functions previously stored in .env
    func <- "filenameWhereSourceCodeIsStored"
    source(paste0("C:/Users/JT/R/Functions/", func, ".R"), .env)
    attach(.env)
    

提交回复
热议问题