You need to enable JavaScript to run this app. R语言从非结构化文本提取动物计数分配至对应列的高效方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

R语言从非结构化文本提取动物计数分配至对应列的高效方法咨询

实现方案

1. tidyverse通用方案(灵活适配多动物类型,无需手动逐个定义列)

这个方案的优势是无需提前知道动物种类,后续新增其他动物类型也不需要修改逻辑,代码可维护性更高:

library(tidyverse)

# 原始数据
dat <- data.frame(
  size = c(50,50,50),
  type = c('50 monkeys', '25 monkeys | 25 apes', '30 monkeys | 10 monkeys | 10 monkeys')
)

# 转换逻辑
dat %>%
  # 按分隔符拆分type列到多行
  separate_longer_delim(type, delim = " | ") %>%
  # 拆分数量和动物种类,自动转数值类型
  separate(type, into = c("count", "animal"), sep = " ", convert = TRUE) %>%
  # 按行聚合同一种动物的数量
  summarise(count = sum(count), .by = c(size, animal)) %>%
  # 转成宽表,缺失值自动填0
  pivot_wider(names_from = animal, values_from = count, values_fill = 0)

2. 高性能data.table方案(适合百万行以上大数据集,执行速度更快)

如果处理的数据量很大,这个方案的执行效率会比tidyverse高3-10倍:

library(data.table)
setDT(dat)

# 转换逻辑
dat[, .(type = unlist(strsplit(type, " \\| "))), by = .(size)][,
  c("count", "animal") := tstrsplit(type, " ", type.convert = TRUE)][,
  dcast(.SD, size ~ animal, value.var = "count", fun.aggregate = sum, fill = 0)
]

3. 固定列简洁写法(仅需要monkeys、apes两列时)

如果确认只有固定两种动物,不需要适配其他类型,可以用更简洁的mutate写法,比你当前的写法可读性更高:

dat %>%
  mutate(
    monkeys = str_extract_all(type, "(\\d+) monkeys") %>% 
      map_dbl(~ sum(as.numeric(str_extract(.x, "\\d+")))),
    apes = str_extract_all(type, "(\\d+) apes") %>% 
      map_dbl(~ sum(as.numeric(str_extract(.x, "\\d+"))))
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:30:00