determining name of object loaded in R

后端 未结 3 1321
滥情空心
滥情空心 2021-02-02 16:55

Imagine you have an object foo that you saved as saved.file.rda as follows:

foo <- \'a\'
save(foo, file=\'saved.file.rda\')
<         


        
相关标签:
3条回答
  • 2021-02-02 17:33

    Assuming there is only one object saved in saved.file.rda, about:

    bar <- load('saved.file.rda')
    the.object <- get(bar)
    

    or just:

    bar <- get(load('saved.file.rda'))
    

    If you want to be "neat" and not pollute your global workspace with the stuff you loaded (and forgot the name of), you can load your object into an environment, and specify that environment in you call to get.

    Maybe:

    temp.space <- new.env()
    bar <- load('saved.file.rda', temp.space)
    the.object <- get(bar, temp.space)
    rm(temp.space)
    ...
    
    0 讨论(0)
  • 2021-02-02 17:42

    As you can read in ?load you can load data to specified environment. Then you could use get and ls to get what you want:

    tmp_env <- new.env()
    load('saved.file.rda', tmp_env)
    get(ls(tmp_env), envir=tmp_env) # it returns only first object in environment
    # [1] "a"
    
    0 讨论(0)
  • 2021-02-02 17:44

    well, i do know a function that eliminates the need to do that (i.e., find the name of the object in the R binary file you just loaded)--in other words, you can use this technique to load R binary files instead of 'load':

    file_path = "/User/dy/my_R_data/a_data_set.RData"
    attach(file_path, pos=2, name=choose_a_name, warn.conflict=T)
    
    • 'warn.conflicts=T' is the default option

    • 'pos=2' is also the default; "2" refers to the position in your search path. For instance, position 1 is ".GlobalEnv." To get the entire array of search paths, use search(). So you would access the search path for the new object by search()[2]

    • use 'detach' to remove the object

    0 讨论(0)
提交回复
热议问题