如何从R中的复杂字符串中提取多个新列(str_sub似乎没有做到这一点)

时间:2016-09-07 21:55:37

标签: r string extract gsub

我正在努力从R中的字符串中提取多个变量。

该列如下所示:

7 digit identifier _ NAME4 digit value - 4 digit value - 4 digit value - location1 - location27-digit identifier _ junk _ junk _ 3 digit value with junk attached

所以例如:

1234567_NAME:0011-1234-0176-town-car:1234567_000001_original_010qyz

我需要新的专栏:

  • 7位数字标识符(" 1234567")

  • NAME

  • 每个4位数值
  • 每个位置
  • 3位数值

str_sub()无法正常工作,因为字符串某些部分的长度是可变的。

我尝试gsub,但由于某些特殊字符会重复多次(即":'和" - ")我无法使用他们提取一个明确定义的字符串部分。

2 个答案:

答案 0 :(得分:1)

为了避免冗长的正则表达式,一个选项是使用str_split_fixed[_:-]作为分隔符将列拆分为矩阵,删除不需要的列并从最后一个中提取数值柱:

s <- "1234567_NAME:0011-1234-0176-town-car:1234567_000001_original_010qyz"
ss <- c(s,s,s)

library(stringr)
mat <- str_split_fixed(ss, "[_:-]", 11)[,-c(9, 10)]
mat
#     [,1]      [,2]   [,3]   [,4]   [,5]   [,6]   [,7]  [,8]      [,9]    
#[1,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010qyz"
#[2,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010qyz"
#[3,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010qyz"

mat[,9] <- sub("(\\d{3}).*", "\\1", mat[,9])
mat
#     [,1]      [,2]   [,3]   [,4]   [,5]   [,6]   [,7]  [,8]      [,9] 
#[1,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010"
#[2,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010"
#[3,] "1234567" "NAME" "0011" "1234" "0176" "town" "car" "1234567" "010"

答案 1 :(得分:1)

如果你保持&#34;冗长的&#34;正则表达式,然后你可以做这样的事情(并在以后添加记录验证,因为你已经嵌入字段长度):

library(stringi)
library(purrr)

pat <- "(.{7})_([[:alnum:][:space:]]+):([[:digit:]]{4})-([[:digit:]]{4})-([[:digit:]]{4})-([[:alnum:][:space:]]+)-([[:alnum:][:space:]]+):([[:digit:]]{7})_[[:alnum:][:space:]]+_[[:alnum:][:space:]]+_([[:digit:]]{3})"

dat <- "1234567_NAME:0011-1234-0176-town-car:1234567_000001_original_010qyz"
dat <- rep(dat, 10)

cols <- c("id", "name", "val1", "val2", "val3", "loc1", "loc2", "val3")

stri_match_all_regex(dat, pat) %>% 
  map_df(~setNames(as.list(.[,c(2:8,10)]), cols))
## # A tibble: 10 x 7
##         id  name  val1  val2  val3  loc1  loc2
##      <chr> <chr> <chr> <chr> <chr> <chr> <chr>
## 1  1234567  NAME  0011  1234   010  town   car
## 2  1234567  NAME  0011  1234   010  town   car
## 3  1234567  NAME  0011  1234   010  town   car
## 4  1234567  NAME  0011  1234   010  town   car
## 5  1234567  NAME  0011  1234   010  town   car
## 6  1234567  NAME  0011  1234   010  town   car
## 7  1234567  NAME  0011  1234   010  town   car
## 8  1234567  NAME  0011  1234   010  town   car
## 9  1234567  NAME  0011  1234   010  town   car
## 10 1234567  NAME  0011  1234   010  town   car