Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store (almost) all objects in workspace in a list

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!

like image 549
Rob Avatar asked Sep 19 '13 14:09

Rob


People also ask

How do I list all objects in R?

ls() function in R Language is used to list the names of all the objects that are present in the working directory.

What statement shows the objects in your workspace R?

The ls() code lists all of the objects in your workspace. The rm() code removes objects in your workspace. You can begin your code with the rm() function to clear all of the objects from your workspace to start with a clean environment.

How to store an object in R?

You can save an R object like a data frame as either an RData file or an RDS file. RData files can store multiple R objects at once, but RDS files are the better choice because they foster reproducible code. To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function.

How do I remove an object from a workspace in R?

rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.


2 Answers

Another option is to use mget:

mget(setdiff(ls(),"B"))
like image 106
agstudy Avatar answered Oct 12 '22 22:10

agstudy


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.

like image 35
juba Avatar answered Oct 13 '22 00:10

juba