簡體   English   中英

將長字符串拆分為較小的字符串

[英]Splitting a Long String into smaller strings

我有一個數據框,其中包含一列數字,如下所示:

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文檔,我無法理清我是如何做到這一點的長度。

你可以使用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)

功能版:

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"

假設這個數據:

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

嘗試這個:

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

如果x是數字然后更換xas.character(x)這一說法。

(哇,與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.

但這很痛苦。 弗洛爾德對此的回答更好。

至於分成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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM