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!
ls() function in R Language is used to list the names of all the objects that are present in the working directory.
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.
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.
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.
Another option is to use mget
:
mget(setdiff(ls(),"B"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With