Ignacio
Ignacio

Reputation: 7938

Extract number inside brackets using regular expression?

Suppose I have a data frame like this one:

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

I want to mutate index so it is a numeric variable with the number inside the brackets. I can do that with this code:

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

I'm sure there is a better way of doing this with regular expressions. Ideally, I would like something that is agnostic to the text before [.

Upvotes: 0

Views: 269

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61164

> 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

Upvotes: 1

Related Questions