如何在R中通过‘arg’匹配并加载以其开头的.RData文件?
arg-Prefixed .RData Files in R Hey there! I totally get why you tried load("arg*.RData") first—wouldn't that be convenient if it worked straight away? Unfortunately, R's load() function doesn't support wildcard patterns like * natively. But we can fix this with a simple two-step approach using base R functions.
Step 1: Find All Matching Files
First, we need to locate every .RData file that starts with arg, even those nested in subfolders. Use list.files() with a regular expression pattern to target these files:
# Get full paths of all arg-prefixed .RData files (including subfolders) target_files <- list.files( pattern = "^arg.*\\.RData$", # Regex to match files starting with "arg" and ending with ".RData" recursive = TRUE, # Look through all subfolders full.names = TRUE # Return full file paths instead of just filenames )
Let's break down the regex pattern:
^arg: Ensures the filename starts exactly with "arg".*: Matches any sequence of characters (of any length) between "arg" and the file extension\\.RData$: Ensures the file ends with.RData(the backslash escapes the dot, which is a special character in regex)
If you don't need to search subfolders, just set recursive = FALSE. You can also specify a specific root folder with the path parameter if needed:
target_files <- list.files( path = "/path/to/your/main/folder", pattern = "^arg.*\\.RData$", recursive = TRUE, full.names = TRUE )
Step 2: Load the Files
Once we have our list of files, we can loop through them and load each one. A for loop is straightforward and lets you add progress messages if you want:
# Load each file into the global environment for (file in target_files) { cat("Loading", basename(file), "...\n") # Optional: Print progress load(file) }
Alternatively, you can use lapply() for a more concise approach:
# Load all files with lapply lapply(target_files, load, envir = .GlobalEnv)
Bonus: Load Objects into a List (Instead of Global Env)
If you prefer to keep all loaded objects organized in a single list (instead of cluttering your global environment), use this variation:
# Load each file's contents into a named list loaded_data <- lapply(setNames(target_files, basename(target_files)), function(file) { temp_env <- new.env() load(file, envir = temp_env) as.list(temp_env) }) # Access objects like this: loaded_data[["arg_233_1_1.RData"]]
That's it! This method will reliably load all your arg-prefixed .RData files without having to specify each one individually.
内容的提问来源于stack exchange,提问作者user321627

