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

R语言按type分组,判断每组cond列是否存在TRUE值

分组判断每组是否存在至少一个TRUE值的几种解法

方法一:dplyr包(tidyverse 常用写法)

通过分组后调用any()函数,快速判断每组cond列是否存在至少一个TRUE:

library(dplyr)

result <- test %>%
  group_by(type) %>%
  summarize(cond = any(cond)) %>%
  ungroup()

print(result)

输出结果:

typecond
aTRUE
bFALSE
cTRUE

方法二:基础R原生实现

无需加载额外包,用aggregate()函数完成分组统计:

result <- aggregate(cond ~ type, data = test, FUN = any)
print(result)

方法三:data.table包(大数据场景更高效)

针对大规模数据集,data.table的分组运算性能更优:

library(data.table)

setDT(test)
result <- test[, .(cond = any(cond)), by = type]
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:45:58