6

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

360010001001002
360010001001004
360010001001005
360010001001006

我想分成 2 位数、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 文档,但我无法按长度整理出我将如何做到这一点。

4

5 回答 5

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)
于 2013-05-07T22:14:53.523 回答
4

假设这些数据:

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

尝试这个:

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

如果x是数字,则在此语句中替换x为。as.character(x)

于 2013-05-08T01:05:27.810 回答
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"
于 2013-05-07T22:32:54.423 回答
0

您可以从stringi包中使用此功能

splitpoints <- cumsum(c(2, 3, 5, 1,4))
stri_sub("360010001001002",c(1,splitpoints[-length(splitpoints)]+1),splitpoints)
于 2014-03-13T11:43:53.233 回答
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 对此的回答更好。

至于拆分成 df 列的实际任务,并有效地做到这一点:

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
于 2014-03-09T15:18:50.003 回答