Store (almost) all objects in the workspace in a list

Let's say that I have many objects in my workspace (global environment), and I want to keep most of them in the list. Here's a simplified example:

# Put some objects in the workspace A <- 1 B <- 2 C <- 3 

I would like to keep objects A and C in a list. Of course, I can do this explicitly:

 mylist <- list(A,C) 

However, when the number of objects in the workspace is very large, it becomes quite cumbersome. Therefore, I would like to do it differently and tried to do the following:

 mylist <- list(setdiff(ls(),B)) 

But this is clearly not what I want, since it only stores the names of objects in the workspace.

Any suggestions on how I can do this?

Thank you very much!

+6
source share
3 answers

Another option is to use mget :

 mget(setdiff(ls(),"B")) 
+10
source

EDIT: I think using lapply / sapply here is causing too many problems. You should definitely use mget answer.

You can try:

 mylist <- sapply(setdiff(ls(),"B"), get) 

In some cases, i.e. if all the objects in your workspace are of the same type, sapply will return a vector. For instance:

 sapply(setdiff(ls(),"B"), get) # AC # 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 

Thus, using lapply instead of sapply here may be safer, as Josh O'Brien pointed out.

+2
source

mget is by far the easiest to use in this situation. However, you can achieve the same value with as.list.environment and eapply :

 e2l <- as.list(.GlobalEnv) # or: e2l <- as.list(environment()) # using environment() within a function returns the function 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 single line:

  (function(x) x[!names(x)%in%"B"])(eapply(environment(), force)) (function(x) x[!names(x)%in%"B"])(as.list(environment())) 
+2
source

Source: https://habr.com/ru/post/954177/


All Articles