regex - Regular expression matching inside dplyr -


when answering this question, wrote following code:

df <- data.frame(call_num = c("hv5822.h4 c47 circulating collection, 3rd floor", "qe511.4 .g53 1982 circulating collection, 3rd floor", "tl515 .m63 circulating collection, 3rd floor", "d753 .f4 circulating collection, 3rd floor", "db89.f7 d4 circulating collection, 3rd floor"))  require(stringr)  matches = str_match(df$call_num, "([a-z]+)(\\d+)\\s*\\.") df2 <- data.frame(df, letter=matches[,2], number=matches[,3]) 

now question is: there simple way combine last 2 lines 1 dplyr call, presumably using mutate()? alternatively, i'd interested in solution do() well. mutate() approach, since we're extracting 2 groups, i'll take solution calls str_match() twice different regular expressions, 1 each desired group.

edit: clarify, main challenge see here str_match returns matrix, , i'm wondering how handle in mutate() or do(). i'm not interested in solutions original problem using other methods of extracting information. there plenty of such solutions given here.

you can try do

df %>%    do(data.frame(., str_match(.$call_num,  "([a-z]+)(\\d+)\\s*\\.")[,-1],                               stringsasfactors=false)) %>%   rename_(.dots=setnames(names(.)[-1],c('letter', 'number'))) #                                             call_num letter number #1     hv5822.h4 c47 circulating collection, 3rd floor     hv   5822 #2 qe511.4 .g53 1982 circulating collection, 3rd floor     qe    511 #3        tl515 .m63 circulating collection, 3rd floor     tl    515 #4          d753 .f4 circulating collection, 3rd floor      d    753 #5        db89.f7 d4 circulating collection, 3rd floor     db     89 

or @samfirke commented, renaming columns can done with

  ---                                    %>%  setnames(., c(names(.)[1], "letter", "number")) 

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -