Parsing a string with multiple brackets

Viewed 74

I have a dataset dt with column "subject", that I need to parse. For example,

ID    subject   

1     USA(Texas)(Austin)
2     USA(California)(Sacramento)

As a result, I want to get the following table:

ID    subject                       Country     State        Capital   

1     USA(Texas)(Austin)            USA         Texas        Austin
2     USA(California)(Sacramento)   USA         California   Sacramento

How can I do it?

1 Answers

Since you have multiple brackets to extract data from you need to make your regex lazy.

library(dplyr)
library(tidyr)

extract(dt, subject, into = c("Country", "State", "Capital"),
              regex = "(.*)\\((.*?)\\)\\((.*)\\)", remove = FALSE)

#  ID                     subject Country      State    Capital
#1  1          USA(Texas)(Austin)     USA      Texas     Austin
#2  2 USA(California)(Sacramento)     USA California Sacramento

Another option with a simpler regex is to remove round brackets with gsub and use separate with sep argument as whitespace.

dt %>%
  mutate(subject = trimws(gsub('[()]', ' ', subject))) %>%
  separate(subject, into = c("Country", "State", "Capital"), sep = "\\s+")

data

dt <- structure(list(ID = 1:2, subject = structure(2:1, 
.Label = c("USA(California)(Sacramento)", "USA(Texas)(Austin)"), 
class = "factor")), class = "data.frame", row.names = c(NA, -2L))
Related