【问题标题】:Extract number inside brackets using regular expression?使用正则表达式提取括号内的数字?
【发布时间】:2018-08-21 16:22:51
【问题描述】:

假设我有一个像这样的数据框:

library(tidyverse)
index <- 1:1000
df1 <- data.frame(index = glue::glue('index[{index}]'),
                  X = rnorm(1000))

我想要mutate 索引,所以它是一个数字变量,括号内是数字。我可以用这段代码做到这一点:

df2 <- df1 %>% mutate(index = gsub(pattern = 'index[', replacement = '', x = index, fixed = T),
                      index = gsub(pattern = ']', replacement = '', x = index, fixed = T),
                      index = as.numeric(index))

我确信使用正则表达式有更好的方法。理想情况下,我想要一些与[ 之前的文本无关的东西。

【问题讨论】:

标签: r regex string dplyr gsub


【解决方案1】:
> df2 <- df1 %>% mutate(index = as.numeric(gsub("index\\[(\\d+)\\]", "\\1", index)))
> df2 %>% head
  index          X
1     1  1.1991921
2     2  0.5474659
3     3 -0.8437927
4     4 -1.8488537
5     5 -0.4673391
6     6 -1.1255241

【讨论】:

  • 有没有办法不使用标准评估使文本与文本无关?例如,如果不是index 我有SomeName
猜你喜欢
  • 2011-07-23
  • 2022-01-17
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多