【发布时间】:2019-02-27 17:55:47
【问题描述】:
我有这样的数据:
library(data.table)
group <- c("a","a","a","b","b","b")
cond <- c("N","Y","N","Y","Y","N")
value <- c(2,1,3,4,2,5)
dt <- data.table(group, cond, value)
group cond value
a N 2
a Y 1
a N 3
b Y 4
b Y 2
b N 5
我想在整个组的条件为 Y 时返回最大值。像这样的:
group cond value max
a N 2 1
a Y 1 1
a N 3 1
b Y 4 4
b Y 2 4
b N 5 4
我尝试将 ifelse 条件添加到分组最大值,但是,当行不满足条件时,我最终只返回 NA 的 no 条件:
dt[, max := ifelse(cond=="Y", max(value), NA), by = group]
【问题讨论】:
-
试试
dt[, max := if(all(cond == "Y")) max(value) else NA, by = group] -
返回了 NA 值的最大列。
-
根据你的描述
would like to return max value when the cond is Y for the entire group.,在例子中不是分组,'a'和'b'都有'N' -
我觉得你需要
dt[, max := max(value[cond == 'Y']), group]
标签: r data.table