Make a list of many objects from a vector of objec

2020-04-26 04:14发布

TL;DR: what I need is a vectorised version of list().

I'm trying to create a list of objects. I don't know how many objects there'll be or what they'll be called, and there may be a large number of them. So I can't just make a list by hand.

However, I know that all the objects will exist in my environment when it comes time to make the list, and I know I will have a character vector containing the names of all the objects.

(These are the outputs of a horrible three-layer for loop that I'm trying to avoid making any bigger. I could just create an empty list and then assign objects to it as the loop creates them, but I'd prefer not to.)

I've searched Google and Stack Overflow, but I can't find a good solution. It seems to me that what I need is a vectorised version of list(): something that will take a vector of object names, find all those objects and shove them in a list.

list(obj1, obj2, obj3) # Not this. I don't want to name each element individually.

objectsVector <- c("obj1", "obj2", "obj3")
list_vectorised(elements = objectsVector) # I want this instead. 

namesVector <- c("anObject", "anotherObject", "yetAnotherObject")
list_vectorised(elements = objectsVector, names  = namesVector) # Or better still, this. 

标签: r
2条回答
孤傲高冷的网名
2楼-- · 2020-04-26 04:43

I found a solution!

foo <- lapply(objectsVector, get) # This creates a list of the objects.
foo <- setnames(foo, namesVector) # This names the elements of the list. 

I'm leaving the question up because I spent so long searching for an answer and want to spare other people the trouble. I'm not sure whether that's the approved thing to do.

查看更多
Melony?
3楼-- · 2020-04-26 04:54

You can use mget to get objects from the environment and put them in a list.

mget(VECTOR_OF_NAMES_OF_OBJECTS)

You can also combine mget with ls() so that you don't have to type the object names your self.

obj1 = 1:2
obj2 = 3:7
obj13 = 8:11

mget(ls(pattern = "obj\\d+"))
#$obj1
#[1] 1 2

#$obj13
#[1]  8  9 10 11

#$obj2
#[1] 3 4 5 6 7
查看更多
登录 后发表回答