user6855566
user6855566

Reputation:

stringr for extract and split

I have a bunch of rows that look like such:

 people <- matrix(c("Joe Smith", "Highland (Baltimore, MD)", "Male", "Jane Davis", "Trinity (Albany, NY)", "Female"), ncol = 3, byrow = T)

The Regex pattern I'm working with is:

cut <- "\\w*\\,\\s.."

That Regex pattern basically reduces the second column to inclue just "Baltimore, MD" and "Albany, NY" so everything inside the parentheses.

Then I want to use str_split to put the city and state into two seperate columns so the final output would look like this:

       [,1]         [,2]       [,3]             [,4]
 [1,] "Joe Smith"  "Highland (Baltimore, MD)" "Male"  
 [2,] "Jane Davis" "Trinity (Albany, NY)"     "Female"

      1         2     3   4
1 Joe Smith Baltimore MD Male
2 Jane Davis Albany NY Female

I just can't quite figure it out.

Upvotes: 1

Views: 251

Answers (4)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Similar to @Onyambu's answer, this one uses extract() rather than a combination of mutate() + sub() + separate():

library(tidyverse)
people %>% 
  as.data.frame() %>%
  extract(V2, into = c("City", "State"), regex = ".*\\((.*), (.*)\\)")
#           V1      City State     V3
# 1  Joe Smith Baltimore    MD   Male
# 2 Jane Davis    Albany    NY Female

You can also use cSplit from my "splitstackshape" package:

library(splitstackshape)
cSplit(as.data.table(people)[, V2 := gsub(".*\\((.*)\\)", "\\1", V2)], "V2", ",")
#            V1     V3      V2_1 V2_2
# 1:  Joe Smith   Male Baltimore   MD
# 2: Jane Davis Female    Albany   NY

Upvotes: 0

akrun
akrun

Reputation: 886978

We can do this with base R

res <- trimws(cbind(people[,1], as.matrix(read.csv(text =
    gsub("^\\S+\\s+\\(|\\)", "", people[,2]), sep=",", header = FALSE)), people[,3]))
colnames(res) <- NULL
res
#    [,1]         [,2]        [,3] [,4]    
#[1,] "Joe Smith"  "Baltimore" "MD" "Male"  
#[2,] "Jane Davis" "Albany"    "NY" "Female"

Upvotes: 0

Dimitrios Zacharatos
Dimitrios Zacharatos

Reputation: 850

people <- matrix(c("Joe Smith", "Highland (Baltimore, MD)", "Male", "Jane Davis", "Trinity (Albany, NY)", "Female"), ncol = 3, byrow = T)
people<-data.frame(people)
res<-data.frame(people,stringr::str_split_fixed(people$X2," ",n=2))
res$X2.1<-gsub(")","",res$X2.1,fixed=TRUE)
res$X2.1<-gsub("(","",res$X2.1,fixed=TRUE)
res<-data.frame(people,stringr::str_split_fixed(res$X2.1,",",n=2))
names(res)<-c("name1","name2","name3","name4","name5")
res$name2<-NULL
res

Upvotes: 0

Onyambu
Onyambu

Reputation: 79208

 library(tidyverse)
people%>%as.data.frame()%>%mutate(V2=sub(".*\\((.*)\\).*","\\1",people[,2]))%>%
    separate(V2,c("City","State"),",")
          V1      City State     V3
1  Joe Smith Baltimore    MD   Male
2 Jane Davis    Albany    NY Female

Upvotes: 3

Related Questions