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

data.table使用patterns筛选列时如何仅选中real_0_h至real_24_h格式列

data.table列筛选解决方案

方法1:优化正则表达式实现精确匹配

你原有代码的正则^real_仅匹配real_前缀,所有符合该前缀的列都会被选中,因此会误纳入real_dose这类非目标列。调整正则规则,严格匹配real_0_h到real_24_h的格式即可,修改后代码如下:

melt(dt, id.vars = c("id", "dose"), measure.vars = patterns("^real_([0-9]|1[0-9]|2[0-4])_h$"))

规则说明:

  • ^real_:限定列名以real_开头
  • ([0-9]|1[0-9]|2[0-4]):限定中间的数字范围为0~24
  • _h$:限定列名以_h结尾,完全匹配目标列格式

方法2:按列位置范围选择(等效于dplyr的:写法)

如果你的数据表中real_0_h到real_24_h是连续按顺序排列的,可以直接通过起止列的位置范围选取,无需编写正则:

# 定位起止列的索引
start_col <- which(names(dt) == "real_0_h")
end_col <- which(names(dt) == "real_24_h")
# 传入范围作为测量列
melt(dt, id.vars = c("id", "dose"), measure.vars = start_col:end_col)

也可以合并为一行写法:

melt(dt, id.vars = c("id", "dose"), measure.vars = which(names(dt) == "real_0_h"):which(names(dt) == "real_24_h"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:15:02