determining name of object loaded in R
Imagine you have an object foo
that you saved as saved.file.rda
as follows:
foo <- 'a'
save(foo, file='saved.file.rda')
Suppose you load saved.file.rda
into an environment with multiple objects but forgot the name of the object that is in saved.file.rda
. Is there 开发者_Python百科a way in R to determine that name?
You can do it the following way, which seems a little clunky:
bar <- load('saved.file.rda')
eval(parse(text=bar)) # this will pull up the object that was in saved.file.rda
However, is there a better way of doing this?
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)
...
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"
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
精彩评论