如何用正则表达式在R中筛选r5至r12开头的变量并生成数据框?
Hey there! Awesome work tackling regex on your first day—let's refine that code into something concise and efficient. Here's how to neatly filter variables starting with r5 through r12 and turn them into a data frame:
Step 1: Use a Targeted Regex to Match Variable Names
We can craft a regex that precisely matches variable names starting with r followed by numbers 5–12. The key is to cover two cases in one pattern: single digits 5-9, and two-digit numbers 10-12.
# Grab all variable names that match our pattern selected_vars <- grep("^r(?:[5-9]|1[0-2])", ls(), value = TRUE)
Let's break down the regex:
^Anchors the match to the start of the variable name (so we don't accidentally match something likexr5e)rMatches the literal letterr(?:[5-9]|1[0-2])A non-capturing group that matches:[5-9]: Any single digit from 5 to 9|: OR1[0-2]: The number 1 followed by 0, 1, or 2 (covers 10, 11, 12)
grep(..., value = TRUE)Returns the actual variable names instead of their indices in the list of variables
Step 2: Create the Data Frame
Once we have the matching variable names, use mget() to fetch their values and wrap them in data.frame():
# Convert selected variables into a data frame df <- data.frame(mget(selected_vars))
Full Example with Sample Data
Here's how it works with your sample variables:
# Simulate your existing variables r1a <- 1:5 r3c <- 6:10 r5e <- 11:15 r7g <- 16:20 r9i <- 21:25 r11k <- 26:30 r13g <- 31:35 r15i <- 36:40 # Filter and create data frame selected_vars <- grep("^r(?:[5-9]|1[0-2])", ls(), value = TRUE) df <- data.frame(mget(selected_vars)) # Check the result print(df)
This will output a data frame containing only r5e, r7g, r9i, and r11k—exactly the variables you want!
Why This is Better
- Conciseness: No need to list every number from 5 to 12 explicitly (great if you ever need to expand the range later)
- Efficiency: The non-capturing group
(?:...)avoids unnecessary group storage, making the regex slightly faster (a small win here, but good practice for larger tasks) - Clarity: The pattern clearly communicates the range you're targeting, making your code easier to read for others (or future you!)
内容的提问来源于stack exchange,提问作者FightMilk

