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

按ID分组删除sBP≥140条件行之后的所有行(R语言)

按ID分组截断数据的解决方案

需求回顾

按ID分组,当某行sBP≥140时,保留该行及之前的所有行,删除该行之后的内容;若无满足条件的行,则保留该ID对应的所有行。


方法一:使用dplyr包(推荐,代码简洁直观)

先加载dplyr包,通过分组、计算截断位置、切片完成处理:

library(dplyr)

# 处理数据
DF_processed <- DF1 %>%
  group_by(ID) %>%
  # 标记每个组中第一个sBP≥140的行索引,无符合条件则为NA
  mutate(first_high = which(sBP >= 140)[1]) %>%
  # 根据first_high的值切片:NA则保留全组,否则保留到目标行
  slice(1:ifelse(is.na(first_high), n(), first_high)) %>%
  # 移除临时辅助列
  select(-first_high) %>%
  # 取消分组
  ungroup()

# 查看处理后的数据
print(DF_processed)

处理结果

# A tibble: 8 × 2
     ID   sBP
  <dbl> <dbl>
1     1   130
2     1   139
3     1   140
4     2   120
5     2   122
6     2   123
7     3   140

方法二:使用Base R(无需额外安装包)

通过split拆分数据组,lapply逐个处理,最后合并结果:

# 按ID拆分数据为列表
id_groups <- split(DF1, DF1$ID)

# 逐个处理每个组
processed_groups <- lapply(id_groups, function(group) {
  # 找到第一个sBP≥140的行索引
  cutoff_idx <- which(group$sBP >= 140)[1]
  # 无符合条件则返回原组,否则截断到目标行
  if (!is.na(cutoff_idx)) {
    group[1:cutoff_idx, ]
  } else {
    group
  }
})

# 合并处理后的组,重置行名
DF_processed_base <- do.call(rbind, processed_groups)
rownames(DF_processed_base) <- NULL

# 查看处理后的数据
print(DF_processed_base)

处理结果

ID sBP
1  1 130
2  1 139
3  1 140
4  2 120
5  2 122
6  2 123
7  3 140

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:32:53