如何用R的tidyverse将ICD-10编码从单行展开为多行?
用tidyverse展开范围型ICD-10编码
可以通过拆分范围边界、生成连续编码序列再展开行的方式实现需求,具体步骤如下:
完整代码实现
library(tidyverse) # 构造示例数据集 df <- tribble( ~ICD_10, ~diagnosis, "A00", "Cholera", "A01-A03", "Other Intestinal infectious diseases", "A15", "Respiratory tuberculosis", "A17-A19", "Other tuberculosis" ) # 处理范围编码并展开 df_expanded <- df %>% # 拆分范围编码为起始/结束值,无范围的行end补NA separate(ICD_10, into = c("start", "end"), sep = "-", fill = "right") %>% # 无范围的行,结束编码等于起始编码 mutate(end = ifelse(is.na(end), start, end)) %>% # 提取编码的字母前缀和数字部分 mutate( prefix = str_extract(start, "[A-Z]"), start_num = as.integer(str_extract(start, "\\d+")), end_num = as.integer(str_extract(end, "\\d+")) ) %>% # 生成连续数字序列,拼接成完整ICD编码(保证数字为两位格式) mutate(ICD_10 = map2(start_num, end_num, ~seq(.x, .y, by = 1)) %>% map_chr(~paste0(prefix, str_pad(.x, width = 2, pad = "0")))) %>% # 将编码序列展开为多行 unnest(ICD_10) %>% # 移除临时辅助列 select(-start, -end, -prefix, -start_num, -end_num) # 查看结果 print(df_expanded)
运行结果
# A tibble: 8 × 2 ICD_10 diagnosis <chr> <chr> 1 A00 Cholera 2 A01 Other Intestinal infectious diseases 3 A02 Other Intestinal infectious diseases 4 A03 Other Intestinal infectious diseases 5 A15 Respiratory tuberculosis 6 A17 Other tuberculosis 7 A18 Other tuberculosis 8 A19 Other tuberculosis
内容的提问来源于stack exchange,提问作者Bobby
相关产品推荐
相关产品推荐

