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

如何从DataFrame提取空格前的数字与符号并生成新列

问题:提取DataFrame字符串中空格前的数字与符号并生成新列

我有一个包含字符列的DataFrame,首列V1为ID列,其余多列包含混合数字、字母、符号的字符串。需要提取字符串中空格前的所有数字与符号,将每列的提取结果用“;”分隔存入对应的新列。

输入数据

df2 <- structure(list(V1 = c("00094", "00001", "00002", "00003", "00004", "00005", "00006", "00007", "00008", "00009"), V2 = c("4-6-2021 (aw), vaccinatie naam en data aangepast 19-8-2021 kv: ic nog niet ontvangen nav eerdere", NA, "23-7 mf: t2-vragenlijst omgezet naar t3, verzoek bij alienke om t2 af te keuren 6-12 mf: corona", NA, NA, "13-12 mf: 3 maanden na 2e vaccinatie corona", "20-7 mf: vaccinatiedatum blijkt enige vaccinatie 6-12 mf: corona", NA, NA, "15-7-2021 kv: corona gehad in maand05 2021, dus één vaccinatie. 6-12 mf: corona"), V3 = c("eerdere brief. mf/sp telefonisch contact laten opnemen. 19-8 mf: gg, herinneringsmail gestuurd, komt niet a", NA, "corona gehad, 1 vaccinatie, per mail", NA, NA, "corona gekregen, per mail", "corona gehad, 1 vaccinatie, per mail", NA, NA, NA)), row.names = c(NA, 10L), class = "data.frame")

解决方案

使用stringr包的字符串匹配功能,先提取所有空格前后的连续字符片段,再筛选出仅包含数字和连字符的有效内容,最后用分号拼接结果。

library(stringr)

# 处理V2列生成dates V2列
df2$`dates V2` <- sapply(df2$V2, function(x) {
  if (is.na(x)) return(NA)
  # 提取所有空格分隔的连续片段
  segments <- str_split(x, "\\s+")[[1]]
  # 筛选仅含数字和连字符的片段
  valid_segs <- segments[str_detect(segments, "^[0-9-]+$")]
  paste(valid_segs, collapse = ";")
})

# 处理V3列生成dates V3列
df2$`dates V3` <- sapply(df2$V3, function(x) {
  if (is.na(x)) return(NA)
  segments <- str_split(x, "\\s+")[[1]]
  valid_segs <- segments[str_detect(segments, "^[0-9-]+$")]
  paste(valid_segs, collapse = ";")
})

# 得到最终结果
df2_new <- df2

输出结果

df2_new <- structure(list(V1 = c("00094", "00001", "00002", "00003", "00004", "00005", "00006", "00007", "00008", "00009"), V2 = c("4-6-2021 (aw), vaccinatie naam en data aangepast 19-8-2021 kv: ic nog niet ontvangen nav eerdere", NA, "23-7 mf: t2-vragenlijst omgezet naar t3, verzoek bij alienke om t2 af te keuren 6-12 mf: corona", NA, NA, "13-12 mf: 3 maanden na 2e vaccinatie corona", "20-7 mf: vaccinatiedatum blijkt enige vaccinatie 6-12 mf: corona", NA, NA, "15-7-2021 kv: corona gehad in maand05 2021, dus één vaccinatie. 6-12 mf: corona"), V3 = c("eerdere brief. mf/sp telefonisch contact laten opnemen. 19-8 mf: gg, herinneringsmail gestuurd, komt niet a", NA, "corona gehad, 1 vaccinatie, per mail", NA, NA, "corona gekregen, per mail", "corona gehad, 1 vaccinatie, per mail", NA, NA, NA), `dates V2` = c("4-6-2021;19-8-2021", NA, "23-7;6-12", NA, NA, "13-12", "20-7;6-12", NA, NA, "15-7-2021;6-12"), `dates V3` = c("19-8", NA, NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -10L), class = "data.frame")

内容的提问来源于stack exchange,提问作者Debbie Oomen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:05:22