用子字符串通配符搜索来查找文本

3

我有一个数据框列,其中包含以下值。 我想使用每个单元格并创建两列-num1和num2,使得num1=“-”之前的所有内容,num2=“-”和“.”之间的所有内容。

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

60-150.PNG
300-12.PNG

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

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

Update

To keep the original column

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

2
akrun教我这个:read.table(text = gsub('-|.PNG', ' ', dat$employee)) - rawr
尝试使用 read.table(text=gsub('-|.PNG', ' ', employ.data$employee), col.names=c('num1', 'num2')) 或者使用 setNames(read.table(text=gsub('-|.PNG', ' ', employ.data$employee)), paste0('num', 1:2)) - akrun
完美。请修改您的答案,我会接受它。 - user2543622
@user2543622 你是不是想在数据集中保留原始列? - akrun
它可以工作。但我不得不将“cbind(employ.data,...”更改为“cbind(employ$data,..”。 - user2543622
显示剩余5条评论

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" 

3

使用stringi的另一个选项

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

2
或者使用简单的 "gsub"。
gsub("-.*", "", employ.data$employee) # substitute everything after - with nothing
gsub(".*-(.*)\\..*", "\\1", employ.data$employee) #keep only anything between - and .

1

strsplit函数会将你想要的内容输出为一个列表。

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

##Output:

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

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

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

1
这可能是类似于 data.frame(lapply(strsplit(sub("\\..*", "", employee), "-"), type.convert)) 的东西。 - David Arenburg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接