You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式在R中筛选r5至r12开头的变量并生成数据框?

Clean Solution to Filter Variables & Create Data Frame in R

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 like xr5e)
  • r Matches the literal letter r
  • (?:[5-9]|1[0-2]) A non-capturing group that matches:
    • [5-9]: Any single digit from 5 to 9
    • |: OR
    • 1[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:03:17