r substring通配符搜索查找文本

时间:2015-04-27 17:10:42

标签: r substring wildcard

我有一个data.frame列,其值如下所示。我想使用每个单元格并创建两个列 - num1和num2,使得num1 =“ - ”之前的所有内容,num2 =“ - ”和“。”之间的所有内容。

我正在考虑使用gregexpr函数,如here所示,并编写一个for循环来迭代每一行。有更快的方法吗?

60-150.PNG
300-12.PNG

employee <- c('60-150.PNG','300-12.PNG')
employ.data <- data.frame(employee)

5 个答案:

答案 0 :(得分:5)

尝试

library(tidyr)
extract(employ.data, employee, into=c('num1', 'num2'),
                    '([^-]*)-([^.]*)\\..*', convert=TRUE)
#   num1 num2
#1   60  150
#2  300   12

或者

library(data.table)#v1.9.5+
setDT(employ.data)[, tstrsplit(employee, '[-.]', type.convert=TRUE)[-3]]
#    V1  V2
#1:  60 150
#2: 300  12

或基于@ rawr的评论

 read.table(text=gsub('-|.PNG', ' ', employ.data$employee),
           col.names=c('num1', 'num2'))
 #   num1 num2
 #1   60  150
 #2  300   12

更新

保留原始列

extract(employ.data, employee, into=c('num1', 'num2'), remove=FALSE,
        '([^-]*)-([^.]*)\\..*', convert=TRUE)
#    employee num1 num2
#1 60-150.PNG   60  150
#2 300-12.PNG  300   12

或者

 setDT(employ.data)[, paste0('num', 1:2) := tstrsplit(employee, 
             '[-.]', type.convert=TRUE)[-3]]
 #     employee num1 num2
 #1: 60-150.PNG   60  150
 #2: 300-12.PNG  300   12

或者

 cbind(employ.data, read.table(text=gsub('-|.PNG', ' ', 
     employ.data$employee),col.names=c('num1', 'num2')))
 #    employee num1 num2
 #1 60-150.PNG   60  150
 #2 300-12.PNG  300   12

答案 1 :(得分:3)

您可以从我的“splitstackshape”软件包中尝试cSplit

library(splitstackshape)
cSplit(employ.data, "employee", "-|.PNG", fixed = FALSE)
#    employee_1 employee_2
# 1:         60        150
# 2:        300         12

由于您提到gregexpr,您可以尝试类似:

do.call(rbind, 
        regmatches(as.character(employ.data$employee), 
                   gregexpr("-|.PNG", employ.data$employee), 
                   invert = TRUE))[, -3]
     [,1]  [,2] 
[1,] "60"  "150"
[2,] "300" "12" 

答案 2 :(得分:3)

使用stringi

的另一个选项
library(stringi)
data.frame(type.convert(stri_split_regex(employee, "[-.]", simplify = TRUE)[, -3]))
#    X1  X2
# 1  60 150
# 2 300  12

答案 3 :(得分:2)

或使用简单的gsub

gsub("-.*", "", employ.data$employee) # substitute everything after - with nothing
gsub(".*-(.*)\\..*", "\\1", employ.data$employee) #keep only anything between - and .

答案 4 :(得分:1)

strsplit功能会为您提供您要查找的内容,并输出到列表中。

employee <- c('60-150.PNG','300-12.PNG')
strsplit(employee, "[-]")

##Output:

[[1]]
[1] "60"      "150.PNG"

[[2]]
[1] "300"    "12.PNG"

注意strsplit的第二个参数是一个正则表达式值,而不仅仅是要拆分的字符,因此可以使用更复杂的正则表达式。