更好的解决方案
library(utils)
raw <- "4878578572809275874037093859845083594859474905704627402739385785748756
0934893758795493758745846784678576857458708476968983984980985974687586
3989458476857609379087685796847586770493706759787398499485957658968590"
# Put your data in a temporary file. You shouldn't have to do this, you data
# is already sitting in a file.
ff <- tempfile()
cat(file = ff, raw)
现在读回来read.fwf
answer <- suppressWarnings(
read.fwf(ff, widths = c(3, 5, 2)))
# Remember to clean up after ourselves.
unlink(ff) # Again, you won't need to do this; your file isn't temporary.
answer
V1 V2 V3
1 487 85785 72
2 93 48937 58
3 398 94584 76
使用正则表达式的初始答案
您可以使用正则表达式(正则表达式)。我已经编码了您在帖子中所说的位置中断:
library(tidyverse)
library(readr)
byRegx <- function(raw){
rawSpl <- str_match(raw[1], "(?x) (^\\d{3}) (\\d{5}) (\\d{2}) (.+)")[1,]
tibble(apples = rawSpl[2], bananas = rawSpl[3], carrots = rawSpl[4],
therestofthem = rawSpl[5])
}
将您的输入读入表格,然后应用该byRegex
功能
inputTbl<- tibble(
raw = readr::read_lines("4878578572809275874037093859845083594859474905704627402739385785748756
0934893758795493758745846784678576857458708476968983984980985974687586
3989458476857609379087685796847586770493706759787398499485957658968590")) %>%
mutate(morecol = map(str_trim(raw), byRegx)) %>%
unnest() %>%
select(- raw)
inputTbl
# A tibble: 3 x 4
# apples bananas carrots therestofthem
# <chr> <chr> <chr> <chr>
# 1 487 85785 72 809275874037093859845083594859474905704627402739385785748756
# 2 093 48937 58 795493758745846784678576857458708476968983984980985974687586
# 3 398 94584 76 857609379087685796847586770493706759787398499485957658968590