如何将案例 ID 添加到列表中,直到它们的累积值达到 R 中的阈值?
How to add the ID of cases to the list until their cumulative value reaches a threshold in R?
我有一个包含两列的 table。第一个具有案例 ID,另一个具有值。我想将 ID 添加到列表中,当累积值达到一个数字(比如 500000)时,应该保存列表并且函数应该从它停止的地方继续直到结束。我怎样才能做到这一点?
例如:
Table:
手机号码:1234 2345 3512 1353 1457 8756
值:5000 3000 498000 23000 485000 23000
输出:
第一名:(1234、2345、3512)
第二名: (1353, 1457)
第三名:(8756)
我希望它足够清楚。提前谢谢你。
复制粘贴代码的数据
ID <- scan(text = "1234 2345 3512 1353 1457 8756")
Value <- scan(text = "5000 3000 498000 23000 485000 23000")
这个有用吗?
library(purrr)
with(df, split(
ID,
cumsum(c(0, head(purrr::accumulate(Value, ~if ((s <- .x + .y) > 500000) 0 else s), -1L)) == 0)
))
df
看起来像这样
> df
ID Value
1 1234 5000
2 2345 3000
3 3512 498000
4 1353 23000
5 1457 485000
6 8756 23000
输出
$`1`
[1] 1234 2345 3512
$`2`
[1] 1353 1457
$`3`
[1] 8756
我有一个包含两列的 table。第一个具有案例 ID,另一个具有值。我想将 ID 添加到列表中,当累积值达到一个数字(比如 500000)时,应该保存列表并且函数应该从它停止的地方继续直到结束。我怎样才能做到这一点?
例如:
Table:
手机号码:1234 2345 3512 1353 1457 8756
值:5000 3000 498000 23000 485000 23000
输出:
第一名:(1234、2345、3512) 第二名: (1353, 1457) 第三名:(8756)
我希望它足够清楚。提前谢谢你。
复制粘贴代码的数据
ID <- scan(text = "1234 2345 3512 1353 1457 8756")
Value <- scan(text = "5000 3000 498000 23000 485000 23000")
这个有用吗?
library(purrr)
with(df, split(
ID,
cumsum(c(0, head(purrr::accumulate(Value, ~if ((s <- .x + .y) > 500000) 0 else s), -1L)) == 0)
))
df
看起来像这样
> df
ID Value
1 1234 5000
2 2345 3000
3 3512 498000
4 1353 23000
5 1457 485000
6 8756 23000
输出
$`1`
[1] 1234 2345 3512
$`2`
[1] 1353 1457
$`3`
[1] 8756