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

R语言如何删除dataframe中按price排序后bucket值非严格递增的行

R语言筛选bucket严格递增行的实现方法

核心逻辑:在已按price降序排序的数据集基础上,只保留bucket值大于所有此前保留行bucket值的记录,最终得到严格递增的bucket序列。


基础R实现

无需安装额外依赖,直接通过循环遍历实现:

# 构造示例数据集
df <- data.frame(
  x = rep(2108, 13),
  year = rep(2010, 13),
  bucket = c(7,2,3,14,13,8,10,5,9,11,16,12,1),
  price = c(100000,95000,93000,92000,91000,90500,89000,88000,87000,86000,85000,84000,83000)
)

# 筛选符合要求的行
keep_flag <- logical(nrow(df))
current_max_bucket <- -Inf
for (i in seq_len(nrow(df))) {
  if (df$bucket[i] > current_max_bucket) {
    keep_flag[i] <- TRUE
    current_max_bucket <- df$bucket[i]
  }
}
result <- df[keep_flag, ]

tidyverse实现

用dplyr+purrr的函数式编程实现,代码更简洁:

library(dplyr)
library(purrr)

result <- df %>%
  # accumulate按顺序计算bucket的累积最大值,和当前bucket相等说明是新增的最大值
  filter(bucket == accumulate(bucket, max))

输出结果验证

两种方法得到的结果完全符合需求:

x year bucket  price
1 2108 2010      7 100000
4 2108 2010     14  92000
11 2108 2010     16  85000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:27:03