将字符串拆分为R中不同长度的子字符串

zon*_*ne1 3 string r

我读过类似的主题,但我的子串有不同的长度(每个9,3,5个字符),因此没有找到任何答案.

我需要将17个字符长的字符串分成三个子字符串,其中第一个长度为9,下一个长度为3,最后一个长度为5个字符.

例:

 N12345671004UN005
 N34567892902UN002 
Run Code Online (Sandbox Code Playgroud)

我想将字符串拆分为三列:

第一个col 9 char.length

"N12345671"      
"N34567892"
Run Code Online (Sandbox Code Playgroud)

第二个col 3 char.length

"004"          
"902"
Run Code Online (Sandbox Code Playgroud)

第三列5字符长

"UN005"  
"UN002"
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

你可以尝试read.fwf指定widths

ff <- tempfile()
cat(file=ff, instr, sep='\n')
read.fwf(ff, widths=c(9,3,5), colClasses=rep('character', 3))
#        V1  V2    V3
#1 N12345671 004 UN005
#2 N34567892 902 UN002
Run Code Online (Sandbox Code Playgroud)

或使用 tidyr/dplyr

library(dplyr)
library(tidyr)
as.data.frame(instr) %>%
       extract(instr, into=paste0('V', 1:3), '(.{9})(.{3})(.{5})')
#         V1  V2    V3
#1 N12345671 004 UN005
#2 N34567892 902 UN002
Run Code Online (Sandbox Code Playgroud)

或组合subread.table

read.table(text=sub('(.{9})(.{3})(.{5})', '\\1 \\2 \\3', instr),
              colClasses=rep('character', 3))
#         V1  V2    V3
#1 N12345671 004 UN005 
#2 N34567892 902 UN002
Run Code Online (Sandbox Code Playgroud)

数据

instr = c("N12345671004UN005", "N34567892902UN002")
Run Code Online (Sandbox Code Playgroud)