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

R语言中基于双条件删除数据框指定行的实操问题

实现方案

核心逻辑如下:

  • 先提取所有Quantity为0的行,记录对应Fund名称和该行的Data作为日期阈值
  • 遍历原始数据集:若该行所属Fund有匹配的阈值,且该行Data小于等于阈值则删除,其余行保留

tidyverse 实现(推荐)

library(dplyr)

# 提取Quantity=0行的阈值映射
zero_q_threshold <- df %>% 
  filter(Quantity == 0) %>% 
  select(Fund, threshold_date = Data)

# 关联过滤得到结果
df_clean <- df %>% 
  left_join(zero_q_threshold, by = "Fund") %>% 
  # 没有阈值的Fund直接保留,有阈值的仅保留日期大于阈值的行
  filter(is.na(threshold_date) | Data > threshold_date) %>% 
  select(-threshold_date)

base R 实现

# 提取阈值映射
zero_q_threshold <- df[df$Quantity == 0, c("Fund", "Data")]
colnames(zero_q_threshold)[2] <- "threshold_date"

# 关联后过滤
df_merge <- merge(df, zero_q_threshold, by = "Fund", all.x = TRUE)
df_clean <- df_merge[is.na(df_merge$threshold_date) | df_merge$Data > df_merge$threshold_date, 
                     setdiff(colnames(df_merge), "threshold_date")]

样例运行效果

对你提供的测试数据执行上述代码后,会删除Fund1下所有日期小于等于2021-08-17的2条记录,最终仅保留Fund2的1条记录,完全匹配需求。

内容的提问来源于stack exchange,提问作者Vinícius Felizatti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:06:00