如何将R中大量以TMC开头的字符对象存入列表?
Hey there! You can easily batch-collect all those TMC-starting character objects into a single list using a couple of R's built-in functions—no need to manually add each one. Here's how:
Step 1: Identify all target object names
First, use ls() with a regular expression to grab every object in your environment that starts with "TMC":
tmc_object_names <- ls(pattern = "^TMC")
The ^TMC regex ensures we only match objects where the name starts exactly with "TMC", which fits your naming pattern perfectly.
Step 2: Batch-retrieve objects into a list
Next, use mget() to fetch all those objects and pack them into a list. This function takes a vector of object names and returns a list where each element is the corresponding object (and keeps the original object names as list names, which is handy for reference):
tmc_collection <- mget(tmc_object_names)
Optional: Filter to only include character objects
If you want to be extra safe (in case there are non-character objects with "TMC" prefixes), you can add a filter to keep only character-type objects:
# Get TMC-named objects, then filter for character type tmc_object_names <- ls(pattern = "^TMC") tmc_char_names <- tmc_object_names[sapply(tmc_object_names, function(obj_name) is.character(get(obj_name)))] tmc_collection <- mget(tmc_char_names)
Verify the result
To check that everything worked as expected, you can inspect the list structure with str() or preview the first few elements with head():
# Check overall structure str(tmc_collection) # Preview first 3 elements head(tmc_collection, 3)
That's it—you'll have all your TMC-prefixed character objects neatly stored in one list!
内容的提问来源于stack exchange,提问作者mightaskalot

