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

拆分R数据框Matches列为三列并按规则填充缺失值

解决方案

首先加载你的数据:

df <- structure(list(Testa = c(-1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L), 
                     Pre = c(NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN), 
                     Fract = c(NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN), 
                     Terms = c(-1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L), 
                     Time = c(NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN), 
                     Matches = c("y15", "b6", "b7", "b11", "y9", "b8(2+)", "y10(3+)", "b12(5+)")), 
                row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))

方法一:使用tidyr+dplyr拆分

利用正则表达式捕获组直接拆分Matches列,同时处理无括号条目的填充:

library(tidyr)
library(dplyr)

df_processed <- df %>%
  # 正则捕获三个目标部分,into指定新列名
  extract(Matches, 
          into = c("Matches_type", "Matches_num", "Matches_count"),
          regex = "^([yb])(\\d+)(?:\\((\\d+)\\+\\))?$",
          remove = FALSE) %>%  # 保留原Matches列,不需要可设为TRUE
  # 把无括号的条目填充为1,并转为整数型
  mutate(Matches_count = ifelse(is.na(Matches_count), 1, as.integer(Matches_count)))

正则表达式说明:

  • ^([yb]):捕获首字符y或b作为第一列
  • (\\d+):捕获字母后的连续数字作为第二列
  • (?:\\((\\d+)\\+\\))?$:非捕获组匹配括号结构,其中(\\d+)捕获括号内数字,?$表示该部分可选(适配无括号的条目)

方法二:使用stringr拆分

如果习惯用字符串处理工具,也可以用str_match提取匹配结果:

library(stringr)

# 提取三部分匹配结果
matches_split <- str_match(df$Matches, "^([yb])(\\d+)(?:\\((\\d+)\\+\\))?$")

# 合并到原数据并处理填充
df_processed <- cbind(df, 
                      as.data.frame(matches_split[,2:4], stringsAsFactors = FALSE) %>%
                        rename(Matches_type = V1, Matches_num = V2, Matches_count = V3) %>%
                        mutate(Matches_count = ifelse(is.na(Matches_count), 1, as.integer(Matches_count))))

处理后的数据示例:

# A tibble: 8 × 9
  Testa  Pre Fract Terms  Time Matches  Matches_type Matches_num Matches_count
  <int> <dbl> <dbl> <int> <dbl> <chr>    <chr>        <chr>               <int>
1    -1  NaN  NaN    -1  NaN   y15      y            15                      1
2    -1  NaN  NaN    -1  NaN   b6       b            6                       1
3    -1  NaN  NaN    -1  NaN   b7       b            7                       1
4    -1  NaN  NaN    -1  NaN   b11      b            11                      1
5    -1  NaN  NaN    -1  NaN   y9       y            9                       1
6    -1  NaN  NaN    -1  NaN   b8(2+)   b            8                       2
7    -1  NaN  NaN    -1  NaN   y10(3+)  y            10                      3
8    -1  NaN  NaN    -1  NaN   b12(5+)  b            12                      5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:35:06