stringr用于提取和拆分

时间:2018-02-21 01:23:57

标签: r regex tidyverse stringr

我有一堆看起来像这样的行:

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

我正在使用的正则表达式是:

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

正则表达式模式基本上减少了第二列,仅包括&#34; Baltimore,MD&#34;和&#34;奥尔巴尼,纽约&#34;所以括号里面的一切。

然后我想使用str_split将城市和州分成两个单独的列,这样最终的输出将如下所示:

       [,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

我无法理解它。

4 个答案:

答案 0 :(得分:3)

 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

答案 1 :(得分:1)

我们可以使用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"

答案 2 :(得分:0)

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

答案 3 :(得分:0)

@Onyambu's answer类似,此版本使用extract()而不是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

您也可以使用我的“splitstackshape”软件包中的cSplit

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