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

如何修改R语言dataframe列:移除group_id列末尾数字

移除dataframe列末尾数字的实现方法

先构造你的示例数据方便测试:

df <- data.frame(
  nCount_RNA = c(11261, 10791, 6477, 6073),
  nFeature_RNA = c(2946, 2689, 1641, 1558),
  percent.mt = c(4.466744, 5.208044, 3.597344, 2.66754),
  rat_clusters = c(1,1,0,0),
  cluster_id = c(1,1,0,0),
  group_id = c("med1", "med1", "SAR1", "SAR1")
)

用dplyr的mutate配合正则表达式就能实现需求,下面提供两种可行方法:


方法1:结合stringr包的str_remove函数

library(dplyr)
library(stringr)

df_modified <- df %>%
  mutate(group_id = str_remove(group_id, "\\d+$"))

方法2:使用base R的sub函数(无需额外加载包)

library(dplyr)

df_modified <- df %>%
  mutate(group_id = sub("\\d+$", "", group_id))

正则表达式说明

  • \\d+:匹配一个或多个数字
  • $:限定只匹配字符串末尾的数字
    两种方法都会精准移除group_id列每个条目末尾的所有数字,得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:57:10