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

R语言dplyr多分组多条件过滤计算最小值返回Inf警告求解

问题描述

需要结合值缺失、非缺失、等于0、大于0等组合条件计算score字段最小值,代码运行时触发警告:min(score) no non missing arguments to min, returning Inf。

业务判定规则

  • 配偶身份判定:sp_id为大于0的非缺失整数变量
  • 产权所有人判定:ownership_percentage大于0且非缺失
  • 优先级规则:若配偶同时满足ownership_percentage大于0且非缺失,优先判定为产权所有人,不归类为配偶

需求说明

已构建测试数据集,因久未使用R语言,现有代码逻辑有误,需修正代码,实现*非产权所有人配偶(满足ownership_percentage为NA或0,且sp_id非缺失/大于0)*分组下的score最小值计算。
现有错误测试代码如下:

library(dplyr)
account_id <-c(1,2,3,4,5,6,7)
principal_id <- c(1,2,3,4,5,6,7)
contact_id <- c(1,2,3,4,5,6,7)
sp_id <-c(1,2,NA,4,5,NA,7)
ownership_percentage <-c(25,0,NA,12,15,67,71)
score <-c(1,2,3,NA,5,6,7)
df <-data.frame(account_id,principal_id,contact_id,sp_id,ownership_percentage,score)

View(df)

# identify Non owner spouses(ownership_percentage = NA or 0) & (sp_id != NA or > 0) 
# calculate min score
df%>%
  group_by(account_id,principal_id,contact_id,sp_id) %>%
  filter(is.na(ownership_percentage) & ownership_percentage == 0 & (is.na(sp_id) || sp_id> 0)) %>%  
  summarise(min_score= min(score))

View(df)

错误点说明

  1. 逻辑判断错误:判断ownership_percentage为NA或0时误用了&(且逻辑),单个值不可能同时为NA和0,导致过滤后无有效样本;判断配偶条件时写反逻辑(非产权配偶要求sp_id非缺失,原代码包含is.na(sp_id)判断),且误用仅支持单值运算的||做向量化判断,会导致逻辑判断仅读取向量第一个元素值,结果完全不符合预期。
  2. 未处理score字段的NA值:min()函数默认遇到NA会返回NA,当组内所有score都是NA时就会触发无有效参数返回Inf的警告。
  3. 过滤逻辑未匹配优先级规则,没有提前排除产权所有人样本。

修正后代码

library(dplyr)

df <- data.frame(
  account_id = c(1,2,3,4,5,6,7),
  principal_id = c(1,2,3,4,5,6,7),
  contact_id = c(1,2,3,4,5,6,7),
  sp_id = c(1,2,NA,4,5,NA,7),
  ownership_percentage = c(25,0,NA,12,15,67,71),
  score = c(1,2,3,NA,5,6,7)
)

result <- df %>%
  filter(
    # 满足配偶身份:sp_id非缺失且大于0
    !is.na(sp_id),
    sp_id > 0,
    # 满足非产权人:产权占比为NA或0,自动排除占比>0的产权所有人,匹配优先级规则
    is.na(ownership_percentage) | ownership_percentage == 0
  ) %>%
  group_by(account_id, principal_id, contact_id, sp_id) %>%
  # 计算最小值时传入na.rm = TRUE,自动移除score中的NA值,避免Inf警告
  summarise(min_score = min(score, na.rm = TRUE), .groups = "drop")

print(result)

基于提供的测试数据集运行后,仅account_id=2的样本符合非产权所有人配偶条件,最终计算得到min_score为2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:12:31