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

如何在R中按多空格拆分含单空格值的字符数据生成表格

处理多空格分隔的R字符型数据转换问题

首先还原提供的原始数据:

my_data <- c("S Leistung Sub Text Ergebnis Einheit Normal Auffällig Katalog Datum Zeit Kommentar ", 
"   APOA_S      Apo A1   1.11   g/l   1.04 - 2.02      01   30.03.2023   06:56   ", 
"  ", "", "   APOB_S      Apo B   1.09   g/l   0.66 - 1.33      01   30.03.2023   06:56   ", 
"  ", "", "   B-BA_E      Basophile Granulozyten absolut   0.04   exp 9/l   0 - 0.1      01   27.03.2023   11:56   ", 
"  ", "", "   B-DBB_E      Differentialblutbild   ·            01   27.03.2023   11:45   ", 
"  ")

针对数据的特点(多空格分隔、字段含单空格、空行、空Sub列),提供两种解决方案:

方法一:tidyverse工具链实现

1. 清理空行并提取表头

先过滤掉无有效内容的空行,再单独处理表头(单空格分隔):

library(tidyverse)

# 移除空行和仅含空格的行
clean_data <- my_data[str_detect(my_data, "\\S")]

# 提取表头:去除首尾空格后按单空格拆分
headers <- clean_data[1] %>% str_squish() %>% str_split(" ", simplify = TRUE)

# 分离数据行(跳过表头行)
data_rows <- clean_data[-1]

2. 按多空格拆分数据并转成数据框

用正则\\s{2,}匹配2个及以上连续空格作为分隔符,拆分后整理成规范数据框:

df <- str_split_fixed(data_rows, "\\s{2,}", n = length(headers)) %>% 
  as.data.frame() %>% 
  setNames(headers) %>% 
  # 去除所有字段前后的多余空格
  mutate(across(everything(), str_squish))

3. 提取目标列

直接筛选需要的Leistung和Ergebnis列,忽略空的Sub列:

target_df <- df %>% select(Leistung, Ergebnis)

# 查看最终结果
print(target_df)

输出结果:

Leistung Ergebnis
1   APOA_S      1.11
2   APOB_S      1.09
3   B-BA_E      0.04
4   B-DBB_E        ·

方法二:基础R实现

无需加载第三方包,用基础R函数完成:

# 清理空行:保留有有效字符的行
clean_data <- my_data[nchar(trimws(my_data)) > 0]

# 提取表头
headers <- strsplit(trimws(clean_data[1]), " ")[[1]]

# 批量拆分数据行:按2个及以上空格分隔
data_list <- lapply(clean_data[-1], function(x) {
  strsplit(trimws(x), "\\s{2,}")[[1]]
})

# 转换为数据框并命名列
df <- do.call(rbind, data_list) %>% as.data.frame()
names(df) <- headers

# 提取目标列
target_df <- df[, c("Leistung", "Ergebnis")]

核心要点

  • 正则表达式\\s{2,}:精准匹配2个及以上连续空格,避免误拆分字段内部的单个空格
  • 空行过滤:必须提前移除无内容的行,防止拆分时出现结构错误
  • 字段去空格:用str_squish()或trimws()清除每个字段前后的冗余空格

内容的提问来源于stack exchange,提问作者Eric G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:50:12