KT_1
KT_1

Reputation: 8474

Extract dataframe column text within brackets

For an example dataframe:

           Name Value
1 Katie (5676W)  <NA>
2  John (2345G)  <NA>
3   Hex (4563W)  <NA>
4  Mike (4564R)  <NA>

df <- structure(list(
          Name = c("Katie (5676W)", "John (2345G)", "Hex (4563W)", 
   "Mike (4564R)"),
          Value = c(NA_character_, NA_character_, NA_character_, NA_character_)),
          .Names = c("Name", "Value"),
          class = c("tbl_df", "tbl", "data.frame"),
          row.names = c(NA, -4L),
          spec = structure(list(
            cols = structure(list(Name = structure(list(), class = c("collector_character", 
      "collector")), Value = structure(list(), class = c("collector_character", 
      "collector"))), .Names = c("Name", "Value")), default = structure(list(), class = c("collector_guess", 
      "collector"))), .Names = c("cols", "default"), class = "col_spec"))

I wish to extract the numbers and letters contained within the bracket and instead add it (minus the brackets to the 'value' column) in the df dataframe.

I have seen how on Stackoverflow to extract it if it was in a vector, but haven't managed to get it working in a dataframe. Any ideas?

Upvotes: 1

Views: 953

Answers (2)

Florian
Florian

Reputation: 25385

You could try the following:

library(qdapRegex)
df$Value = rm_between(df$Name, '(', ')', extract=TRUE)

output:

           Name Value
1 Katie (5676W) 5676W
2  John (2345G) 2345G
3   Hex (4563W) 4563W
4  Mike (4564R) 4564R

Hope this helps!

Upvotes: 1

kath
kath

Reputation: 7724

You can do it like this: (I use the stringr-package, but it can be done in base R, too)

library(stringr)
df$Value <- str_extract(df$Name, "\\(.*\\)")
df$Value <- str_remove_all(df$Value, "[\\(\\)]")

df
# A tibble: 4 x 2
#   Name          Value
#   <chr>         <chr>
# 1 Katie (5676W) 5676W
# 2 John (2345G)  2345G
# 3 Hex (4563W)   4563W
# 4 Mike (4564R)  4564R

With base R you can do:

df$Value <- sub("(.*\\()(.*)(\\))", "\\2", df$Name)

Upvotes: 0

Related Questions