【问题标题】:group elements in a list of numbers according to a threshold in R根据 R 中的阈值对数字列表中的元素进行分组
【发布时间】:2021-03-26 07:53:10
【问题描述】:

假设我有一个数字列表:

numbers = c(1, 2, 5, 6, 3, 2, 3, 7, 6)

和一个阈值

threshold = 6

我想根据阈值对数字列表中的元素进行分组——对元素求和,直到达到/超过阈值。保存每个组的第一个元素的索引,所以想要的输出是:

1, 4, 5, 8, 9

1 因为它是开始

4 因为 1+2+5 = 8 > 6,这包括 3 个元素

它类似于这篇文章Sum list of numbers until threshold,但我们希望继续添加,直到到达列表末尾。

【问题讨论】:

标签: r


【解决方案1】:

您可以使用 MESS 包中的函数 cumsumbinning

numbers = c(1, 2, 5, 6, 3, 2, 3, 7, 6)
threshold = 6
which(!duplicated(MESS::cumsumbinning(numbers, threshold - 1, cutwhenpassed=TRUE), fromLast = TRUE))
#[1] 3 4 7 8 9

如果你想要组中的第一个元素。

which(!duplicated(MESS::cumsumbinning(numbers, threshold - 1, cutwhenpassed=TRUE)))
#[1] 1 4 5 8 9

cumsumbinningcutwhenpassed=TRUE 会在值通过 threshold 值时创建一个新组,因此我使用了threshold - 1

MESS::cumsumbinning(numbers, threshold - 1, cutwhenpassed=TRUE)
#[1] 1 1 1 2 3 3 3 4 5

【讨论】:

  • 在没有 MESS 包的情况下还有其他方法吗?下载 MESS 包时,我不断收到错误消息。
  • 我能想到的另一种方式是混乱的循环。您在下载软件包时遇到什么问题?我在尝试回答这个问题时自己安装了它,我可以使用 install.packages('MESS') 毫无问题地下载它
  • 我收到很多错误,例如ERROR: dependencies 'glmnet', 'kinship2' are not available for package 'MESS'
  • 我认为主要问题是这一行cannot find -lgfortran
【解决方案2】:

我认为这也可以达到目的

library(purrr)
setdiff(which(accumulate(numbers, ~ifelse(.x + .y <  6, .y + .x, 0)) ==0), which(numbers == 0))

#check on new vector numbers
numbers = c(1, 2, 5, 6, 3, 2, 3, 7, 6, 0, 2, 3, 7, 1, 2)

setdiff(which(accumulate(numbers, ~ifelse(.x + .y <  6, .y + .x, 0)) ==0), which(numbers == 0))
[1]  3  4  7  8  9 13

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多