0

Trying to extract data from data frame Sample Column:

Second
Daughter (Birth)
No Relation
Son (Adopted)

Desired output (two column):

Data1            Data2
Daughter        (Birth)
No relation
Son             (Adopted)

using this command but not getting the results:

as.data.frame(sub(".*\\w+[^)]*?(\\w+)\\).*", "\\1", test1$second))

Any suggestions or help is appreciated.

neilfws
  • 32,751
  • 5
  • 50
  • 63
scorpionz
  • 35
  • 1
  • 1
  • 7
  • `library(stringr); str_extract(test1$second, "\\((.*?)\\)")` from [here](https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets). – Ronak Shah Dec 19 '17 at 03:53
  • Do you really want the parentheses around the data in `Data2`? – Stuart Allen Dec 19 '17 at 04:15
  • Yes, Parentheses is a part of the data. – scorpionz Dec 19 '17 at 04:48
  • @Ronak Shah Thanks for your suggestions, based on above suggestions, I was able to get the desired results. Please let me know if this can can be improved or optimized to something smaller. `code` test1 <- data.frame(second = c("Daughter (Birth)", "No Relation", "Son (Adopted)")) test1[2] <- data.frame(gsub("\\((.*?)\\)", "", test1$second)) test1[3] <- data.frame(str_extract(test1$second, "\\((.*?)\\)")) colnames(test1)[2] <- "data1" colnames(test1)[3] <- "data2" `code` – scorpionz Dec 19 '17 at 05:47
  • `test1$data2 <- str_extract(test1$second, "\\((.*?)\\)")` should do it. – Ronak Shah Dec 19 '17 at 06:14

0 Answers0