You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含字符与数字的向量拆分为数据框列?

问题:PDF提取表格的字符数字拆分与误识别修复

我需要把从PDF提取的包含字符与数字的向量拆分为列,目标是创建包含unit、year、pct_income列的数据框,其中unit为左侧分类(如Government等)。目前已完成文本提取并去除空格和点号,但存在数字1被误识别为"i"或"I"的问题,求后续处理方法。

初始代码

library(tidyverse)
table_raw <- c("Per cent of Total Income",
               "1938-39 1945 1965",
               "Government                      ................          62     50      6I",
               "Insured          persons            .....   ...........     i6    28    22",
               "Employers                    ................          19      20       15",
               "Other (mainly interest) ......... ....... 3 2 2")


table_raw %>% 
  # 将点号替换为空格
  str_replace_all("\\.", " ") %>% 
  
  # 将两个及以上空格替换为单个空格
  str_replace_all("\\s{2,}", " ")

解决方案(感谢Peter的解答)

library(tidyverse)

table_raw <- c("Per cent of Total Income",
                     "1938-39 1945 1965",
                     "Government                      ................          62     50      6I",
                     "Insured          persons            .....   ...........     i6    28    22",
                     "Employers                    ................          19      20       15",
                     "Other (mainly interest) ......... ....... 3 2 2")

# --- 数据清洗步骤 ---#

# 移除前两行(标题和年份行)
vec <- table_raw [-c(1:2)] %>%
  str_replace_all("\\.", " ") %>% 
  # 清除所有多余空白(首尾及中间连续空格)
  str_squish() %>% 
  # 匹配位于数字前的'i'或'I',替换为'1'
  str_replace_all("[iI](?=\\d)", "1") %>% 
  # 匹配位于数字后的'i'或'I',替换为'1'
  str_replace_all("(?<=\\d)[iI]", "1") %>% 
  # 将单个数字前的空格替换为逗号,为后续列拆分做标记
  str_replace_all("\\s(?=\\d{1})", ",")


final <- data.frame(unit = vec) %>% 
  separate(col = unit, sep = ",", into = c("unit_of_observation", "1938-39", "1945", "1965")) |> 
  pivot_longer(-unit_of_observation, names_to = "year", values_to = "pct_income")

内容的提问来源于stack exchange,提问作者Tomas R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:50:38