r 子字符串通配符搜索以查找文本

r substring wildcard search to find text

我有一个 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)

尝试

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

strsplit函数会给你你要找的东西,输出到一个列表。

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

##Output:

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

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

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

您可以尝试 cSplit 来自我的 "splitstackshape" 包:

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" 

或者使用简单的 gsub.

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

另一个选项使用 stringi

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