我有一个数据框列,其中包含以下值。 我想使用每个单元格并创建两列-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)
尝试
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
read.table(text=gsub('-|.PNG', ' ', employ.data$employee),
col.names=c('num1', 'num2'))
# num1 num2
#1 60 150
#2 300 12
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
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"
使用stringi
的另一个选项
library(stringi)
data.frame(type.convert(stri_split_regex(employee, "[-.]", simplify = TRUE)[, -3]))
# X1 X2
# 1 60 150
# 2 300 12
gsub("-.*", "", employ.data$employee) # substitute everything after - with nothing
gsub(".*-(.*)\\..*", "\\1", employ.data$employee) #keep only anything between - and .
strsplit
函数会将你想要的内容输出为一个列表。
employee <- c('60-150.PNG','300-12.PNG')
strsplit(employee, "[-]")
##Output:
[[1]]
[1] "60" "150.PNG"
[[2]]
[1] "300" "12.PNG"
strsplit
的第二个参数是一个正则表达式值,不仅仅是要拆分的字符,因此可以使用更复杂的正则表达式。data.frame(lapply(strsplit(sub("\\..*", "", employee), "-"), type.convert))
的东西。 - David Arenburg
read.table(text = gsub('-|.PNG', ' ', dat$employee))
- rawrread.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