按数据表上的最后一个空格拆分字符串

时间:2015-03-19 17:53:18

标签: r string split data.table

我有一个包含2列的数据表:

             term  freq
1:    a arena tour    1
2: a available why    1
3:     a backup in    1
4:       a bad ass    1
5:     a bad chick    1

我希望将“term”列拆分为最后一个空格,例如:

         termA  termB freq
1:     a arena   tour    1
2: a available    why    1
3:    a backup     in    1
4:       a bad  chick    1

我尝试使用“str”(代码bellow),它仅对字符串起作用,但对data.date不起作用(似乎在所有行上使用相同的索引)

data.table (termA = substr(dt_n3$term, 1, rev(gregexpr("\\ ", dt_n3$term)[[1]])[1]-1),
                         termB = substr(dt_n3$term, rev(gregexpr("\\ ", dt_n3$term)[[1]])[1], 1000),
                         freq = dt_n3$freq)

无论如何,我不认为这是最好的方法。 有人可以帮我吗? 感谢

3 个答案:

答案 0 :(得分:7)

您可以尝试data.table v 1.9.5

中的tstrsplit功能
DT[, paste0('term', LETTERS[1:2]) := tstrsplit(term, ' (?=[^ ]*$)',
                                     perl=TRUE)][, term:=NULL][]
#   freq       termA termB
#1:    1     a arena  tour
#2:    1 a available   why
#3:    1    a backup    in
#4:    1       a bad   ass
#5:    1       a bad chick

数据

DT <- data.table(term= c("a arena tour", "a available why", 
      "a backup in", "a bad ass", "a bad chick"), freq=1)

稍加修改的版本,您可以在同一语句中进行分配和删除:

cols = c("term", paste0("term", LETTERS[1:2]))
DT[, (cols) := c(list(NULL), tstrsplit(term, ' (?=[^ ]*$)', perl=TRUE))]

NULL分配给term会删除该列。

答案 1 :(得分:2)

使用sub可以分两步完成。

dt = data.table(term = c("a arena tour","a available why","a bad ass"), freq=1)

# erase last part
dt[, termA := sub(" [^ ]*$", "", term)]

# erase first part
dt[, termB := sub(".* ", "", term)]

答案 2 :(得分:0)

使用stringi包:

x <- c("ala ma kota", "this is text")
stri_locate_last_fixed(x, " ")
##      start end
## [1,]     7   7
## [2,]     8   8
splitHere <- stri_locate_last_fixed(x, " ")
stri_sub(x, to= splitHere[,1]-1)
## [1] "ala ma"  "this is"
stri_sub(x, from= splitHere[,1]+1)
## [1] "kota" "text"
cbind(stri_sub(x, to= splitHere[,1]-1), stri_sub(x, from=splitHere[,1]+1))
##      [,1]      [,2]  
## [1,] "ala ma"  "kota"
## [2,] "this is" "text"