使用 R 从字符中提取行、文本和数字

Extracting row, text and numbers from character with R

需要从文本中提取数据(这只是一个示例)

text <- c("    9 A                  1427107                -", 
              "    99 (B)                3997915                -", 
              "    999 (SOCIO)            7161315                -", 
              "    9999 @M                 4035115                -", 
              "    99999 01 Z               2136481035115         8,621" 
              )

到目前为止我尝试了但无法为所有列创建模式

as.numeric(gsub("([0-9]+).*$", "\1",text))

我希望我的数据框看起来像

row_names   Text        ID              Amount
9           A           1427107         - 
99          (B)         3997915         - 
999         (SOCIO)     7161315         -
9999        @M          4035115         - 
99999       01 Z        2136481035115   8,621

Row_names都是数字,“文字”包含数字和文字 ID 列包含 7 到 13 位数字, 金额是“-”或带有千位 (,)

的数字

我们可以使用read.table将数据读入data.frame

df1 <- read.table(text =  text, header = FALSE, fill = TRUE)

或使用extract

library(tibble)
library(tidyr)
tibble(col1 = trimws(text)) %>% 
    extract(col1, into = c('rn', 'Text', 'ID', 'Amount'),
        '^(\d+)\s+(.*)\s+(\d+)\s+([-0-9,]+)', convert = TRUE)

在 base R 中,我们可以使用 strcapture 并提供要提取的数据的模式和类型。

strcapture('\s+(\d+)\s(.*?)\s+(\d+)\s(.*)', text, 
           proto=list(row_names=integer(), Text=character(), 
                      ID = numeric(), Amount = character()))

#  row_names    Text            ID           Amount
#1         9       A       1427107                -
#2        99     (B)       3997915                -
#3       999 (SOCIO)       7161315                -
#4      9999      @M       4035115                -
#5     99999    01 Z 2136481035115            8,621