通过正则表达式将矢量分割成数据帧

时间:2016-11-17 20:47:26

标签: r regex vector strsplit

我有一个看起来像这样的载体

head(val)
[1] "PD2323 [403-407]"   "P05230 [455-459]"

我想将它拆分为一个包含3列和多行的数据框。输出应该如下所示:

head(output)
              [,1]       [,2]       [,3]       
    [1,] "P20700"         403        407
    [2,] "P05787"         455        459
    [3,] "O14641"         168        178

然而,当我尝试设置它时,我最终得到一个超过3列的矩阵

head(strsplit(val, "\\s+"))

[[1]]
[1] "PD2323"    "[403-407]"

[[2]]
[1] "P05230"    "[455-459]"

[[3]]
[1] "AS14641"    "[168-178]"

[[4]]
[1] "SS7Z3Z4"    "[424-428]"

[[5]]
[1] "QQN4C6-2"  "[671-679]"

[[6]]
[1] "DD9Y3B2" "[7-13]

起初看起来很有希望,

do.call(rbind, head(strsplit(val, "\\s+")))
     [,1]       [,2]       
[1,] "PD2323"   "[403-407]"
[2,] "P05230"   "[455-459]"
[3,] "AS14641"   "[168-178]"
[4,] "SS7Z3Z4"   "[424-428]"
[5,] "QQN4C6-2" "[671-679]"
[6,] "DD9Y3B2"   "[7-13]"   

如果我现在删除头部功能,我最终因某种原因得到了90列的内容

dim(do.call(rbind, strsplit(val, "\\s+")))

[1] 23369    90
Warning message:
In .Method(..., deparse.level = deparse.level) :
  number of columns of result is not a multiple of vector length (arg 314)

1 个答案:

答案 0 :(得分:2)

我们可以使用gsub删除方括号和-,并使用data.frame

读入read.table
d1 <- read.table(text=gsub("[][]|-", " ", val), header=FALSE, stringsAsFactors=FALSE)
d1 
#    V1  V2  V3
#1 PD2323 403 407
#2 P05230 455 459

数据

val <- c( "PD2323 [403-407]",   "P05230 [455-459]")