让我们想象一下,我想创建一个data.table,其中包含三列mtcars
。我想要一个cost
(用于说明目的是hp的总和),按分组gear
。问题是第三个变量costlimited
-它取决于先前指定的变量budget
。如果cost
> budget
,则costlimited
= budget
,否则costlimited
= cost
。
budget <- c(2000)
mtcarsTOTAL <- mtcars[, ':=' ( cost = sum(hp), costlimited = ifelse(cost > budget, budget, cost) ), by = gear]
另外,我想添加一列,如果成本>预算,则包含1,否则,则包含0。理想的结果是
gear cost costLimited highCost
[1,] 4 1074 1074 0
[2,] 3 2642 2000 1
[3,] 5 978 978 0
重点是在data.table中执行此操作,我目前正在这样做。
您不需要ifelse
这里。(顺便说一句,fifelse
来自data.table
。)
尝试
library(data.table)
budget <- c(2000)
dt <- as.data.table(mtcars)[, .(cost = sum(hp)), by = gear]
dt[, costlimited := pmin(budget, cost)]
dt[, highCost := +(budget == costlimited)]
dt
# gear cost costlimited highCost
#1: 4 1074 1074 0
#2: 3 2642 2000 1
#3: 5 978 978 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句