如何用IfElse或Case_When在R中提取数据生成两列?
从Pitcnt列提取数字的解决方案
使用case_when实现
你可以在mutate中通过case_when根据字符串长度分别提取对应位置的数字,同时提取开头的1-2位数字:
library(dplyr) # 示例数据 pc <- structure(list(Pitcnt = c("12 (3-2)", "7 (0-1)", "3 (0-2)", "8 (3-2)", "5 (2-2)", "7 (3-2)", "1 (0-0)", "2 (0-1)", "5 (1-2)", "10 (3-2)"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L)) # 处理数据 pc_processed <- pc %>% mutate( # 提取开头的1或2位数字 start_num = as.numeric(ifelse(nchar(Pitcnt) == 8, substr(Pitcnt, 1, 2), substr(Pitcnt, 1, 1))), # 根据字符串长度提取短横线前的数字到x列 x = case_when( nchar(Pitcnt) == 8 ~ as.numeric(substr(Pitcnt, 5, 5)), nchar(Pitcnt) == 7 ~ as.numeric(substr(Pitcnt, 4, 4)) ), # 根据字符串长度提取短横线后的数字到y列 y = case_when( nchar(Pitcnt) == 8 ~ as.numeric(substr(Pitcnt, 7, 7)), nchar(Pitcnt) == 7 ~ as.numeric(substr(Pitcnt, 6, 6)) ) ) print(pc_processed)
基于正则表达式的更优方案
依赖字符串长度的方式不够灵活,使用正则表达式捕获组可以直接定位需要的数字,无需判断长度:
library(dplyr) library(tidyr) pc_processed <- pc %>% # 正则表达式捕获三个目标数字:开头1-2位、短横线前后各1位 extract(Pitcnt, into = c("start_num", "x", "y"), regex = "^(\\d{1,2}) \\((\\d)-(\\d)\\)", convert = TRUE) # 自动转换为数值类型 print(pc_processed)
输出结果
两种方法都会得到如下结果:
# A tibble: 10 × 3 start_num x y <int> <int> <int> 1 12 3 2 2 7 0 1 3 3 0 2 4 8 3 2 5 5 2 2 6 7 3 2 7 1 0 0 8 2 0 1 9 5 1 2 10 10 3 2
内容的提问来源于stack exchange,提问作者Metsfan
相关产品推荐
相关产品推荐

