问题
Let's say that I have many objects in my workspace (global environment) and I want to store most of those in a list. Here's a simplified example:
# Put some objects in the workspace
A <- 1
B <- 2
C <- 3
I would like to store objects A and C in a list. Of course, I can do that explicitly:
mylist <- list(A,C)
However, when the number of objects in the workspace is very large, this would become rather cumbersome. Hence, I would like to do this differently and attempted the following:
mylist <- list(setdiff(ls(),B))
But this obviously is not what I want, as it only stores the names of the objects in the workspace.
Any suggestions on how I can do this?
Many thanks!
回答1:
Another option is to use mget
:
mget(setdiff(ls(),"B"))
回答2:
EDIT : I think using lapply
/ sapply
here raises too many problems. You should definitely use the mget
answer.
You can try :
mylist <- sapply(setdiff(ls(),"B"), get)
In certain cases, ie if all the objects in your workspace are of the same type, sapply
will return a vector. For example :
sapply(setdiff(ls(),"B"), get)
# A C
# 1 3
Otherwise, it will return a list :
v <- list(1:2)
sapply(setdiff(ls(),"B"), get)
# $A
# [1] 1
#
# $C
# [1] 3
#
# $v
# [1] 1 2
So using lapply
instead of sapply
here could be safer, as Josh O'Brien pointed out.
回答3:
mget
is definitely the easiest to use in this situation. However, you can achieve the same with as.list.environment
and eapply
:
e2l <- as.list(.GlobalEnv)
# or: e2l <- as.list(environment())
# using environment() within a function returns the function's env rather than .GlobalEnv
e2l[! names(e2l) %in "B"]
# the following one sounds particularly manly with `force`
e2l <- eapply(environment(), force)
e2l[! names(e2l) %in "B"]
And one-liners:
(function(x) x[!names(x)%in%"B"])(eapply(environment(), force))
(function(x) x[!names(x)%in%"B"])(as.list(environment()))
来源:https://stackoverflow.com/questions/18897473/store-almost-all-objects-in-workspace-in-a-list