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
相关产品推荐
相关产品推荐

