将长字符串拆分为较小的字符串

时间:2013-05-07 22:07:18

标签: string r split

我有一个数据框,其中包含一列数字:

360010001001002
360010001001004
360010001001005
360010001001006

我想分成两位数,3位数,5位数,1位数,4位数的块:

36 001 00010 0 1002
36 001 00010 0 1004
36 001 00010 0 1005
36 001 00010 0 1006

这似乎应该是直截了当的,但我正在阅读strsplit文档,我无法理清我是如何按长度做的。

5 个答案:

答案 0 :(得分:8)

您可以使用substring(假设字符串/数字的长度是固定的):

xx <- c(360010001001002, 360010001001004, 360010001001005, 360010001001006)
out <- do.call(rbind, lapply(xx, function(x) as.numeric(substring(x, 
                     c(1,3,6,11,12), c(2,5,10,11,15)))))
out <- as.data.frame(out)

答案 1 :(得分:4)

功能版:

split.fixed.len <- function(x, lengths) {
   cum.len <- c(0, cumsum(lengths))
   start   <- head(cum.len, -1) + 1
   stop    <- tail(cum.len, -1)
   mapply(substring, list(x), start, stop)
}    

a <- c(360010001001002,
       360010001001004,
       360010001001005,
       360010001001006)

split.fixed.len(a, c(2, 3, 5, 1, 4))
#      [,1] [,2]  [,3]    [,4] [,5]  
# [1,] "36" "001" "00010" "0"  "1002"
# [2,] "36" "001" "00010" "0"  "1004"
# [3,] "36" "001" "00010" "0"  "1005"
# [4,] "36" "001" "00010" "0"  "1006"

答案 2 :(得分:4)

假设这个数据:

x <- c("360010001001002", "360010001001004", "360010001001005", "360010001001006")

试试这个:

read.fwf(textConnection(x), widths = c(2, 3, 5, 1, 4))

如果x是数字,则在此声明中将x替换为as.character(x)

答案 3 :(得分:0)

(哇,与Python相比,这个任务非常笨拙和痛苦.Anyhoo ......)

PS我现在看到你的主要目的是将子串长度的矢量转换为索引对。 您可以使用cumsum(),然后将索引排在一起:

ll <- c(2,3,5,1,4)
sort( c(1, cumsum(ll), (cumsum(ll)+1)[1:(length(ll)-1)]) )
# now extract these as pairs.

但这很痛苦。 flodel的答案更好。

关于分裂成d.f.的实际任务列,并有效地做到这一点:

stringr::str_sub()优雅地与plyr::ddply() / ldply

结合
require(plyr)
require(stringr)

df <- data.frame(value=c(360010001001002,360010001001004,360010001001005,360010001001006))
df$valc = as.character(df$value)

df <- ddply(df, .(value), mutate, chk1=str_sub(valc,1,2), chk3=str_sub(valc,3,5), chk6=str_sub(valc,6,10), chk11=str_sub(valc,11,11), chk14=str_sub(valc,12,15) )

#             value            valc chk1 chk3  chk6 chk11 chk14
# 1 360010001001002 360010001001002   36  001 00010     0  1002
# 2 360010001001004 360010001001004   36  001 00010     0  1004
# 3 360010001001005 360010001001005   36  001 00010     0  1005
# 4 360010001001006 360010001001006   36  001 00010     0  1006

答案 4 :(得分:0)

您可以使用stringi package

中的此功能
splitpoints <- cumsum(c(2, 3, 5, 1,4))
stri_sub("360010001001002",c(1,splitpoints[-length(splitpoints)]+1),splitpoints)