Regex group capture in R with multiple capture-groups

In R, is it possible to extract group capture from a regular expression match? As far as I can tell, none of grep , grepl , regexpr , gregexpr , sub , or gsub return the group captures.
In the data frame below, I want to create a new column or a new data frame such that A1 and B1 are subgroups. for example, A1 would have REF, FOW and NIGHT as it's element and B2 would have NURT, PEGGY and PILLAR. Is there a package that can do that?

NAME <- c("HUGHES", "BAKER", "STONEBOY", "FINN", "BANNY", "GRANT")
ACCOUNT_NO <- c( 003, 004, 005, 006, 007, 008)
kv33 <- c( "A1", "B2", "B2", "A1", "A1", "B2")
KV11 <- c("REF", "NURT", "PEGGY"," FOW","NIGHT", "PILLAR")
(Companies_data <- data.frame(NAME,ACCOUNT_NO,kv33,KV11))
#>       NAME ACCOUNT_NO kv33   KV11
#> 1   HUGHES          3   A1    REF
#> 2    BAKER          4   B2   NURT
#> 3 STONEBOY          5   B2  PEGGY
#> 4     FINN          6   A1    FOW
#> 5    BANNY          7   A1  NIGHT
#> 6    GRANT          8   B2 PILLAR

I am sorry, I do not understand how you want to transform the data frame. However, you can use group captures with regex in R. Here is a simple example with sub() where text that starts with three digits, then has non-digits, then has a digit is replaced with just the non-digits.

> TEXT <- c("12HERE56", "123THERE4", "WHERE", "12Those389these9", "that345")
> sub(pattern = "\\d{3}([^\\d]+)\\d",replacement = "\\1", x = TEXT)
[1] "12HERE56"     "THERE"        "WHERE"        "12Thosethese" "that345"

Is that the kind of thing you are looking for?

No. But thanks, I appreciate.


library(tidyverse)

df2<-group_by(Companies_data,
         kv33) %>% mutate(kv11_lists = list(KV11))

df2$kv11_lists

# [1]]
# [1] REF    FOW  NIGHT
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF
# 
# [[2]]
# [1] NURT   PEGGY  PILLAR
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF
# 
# [[3]]
# [1] NURT   PEGGY  PILLAR
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF
# 
# [[4]]
# [1] REF    FOW  NIGHT
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF
# 
# [[5]]
# [1] REF    FOW  NIGHT
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF
# 
# [[6]]
# [1] NURT   PEGGY  PILLAR
# Levels:  FOW NIGHT NURT PEGGY PILLAR REF

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.