如何简化R语言中多模式匹配的rm函数代码以优化编程写法?
rm() Calls in R Great question! Repeating identical rm() calls with minor pattern changes is definitely unnecessary—let's clean this up to follow better coding practices (like DRY: Don't Repeat Yourself).
One-Line Simplification
You can combine all your prefix patterns into a single regular expression and call rm() just once:
rm(list = ls(pattern = "^(DC|HX|Time|Code)"))
Here's how the regex works:
^anchors the match to the start of the object name (so we only catch names that begin with these prefixes)(DC|HX|Time|Code)is a group that matches any of the four prefixes you specified
More Scalable Approach
If you ever need to add/remove prefixes later, storing them in a vector makes maintenance even easier:
# Define your prefixes in one place target_prefixes <- c("DC", "HX", "Time", "Code") # Build the regex pattern dynamically cleanup_pattern <- paste0("^(", paste(target_prefixes, collapse = "|"), ")") # Remove all matching objects rm(list = ls(pattern = cleanup_pattern))
This way, you only need to edit the target_prefixes vector instead of hunting through multiple rm() calls if your needs change.
Both approaches cut down on redundant code, make your intent clearer at a glance, and align with cleaner R programming habits.
内容的提问来源于stack exchange,提问作者Infernez

