gpt4 book ai didi

r - 金额(仅限整数)在不同桶中的分布组合

转载 作者:行者123 更新时间:2023-12-01 09:18:10 26 4
gpt4 key购买 nike

假设有 5 个桶 (1 - 5),并且为每个桶分配一个(整数)值。例如

> bucket = 1:5
> value = c(14, 12, 9, 20, 7)
> data.frame(bucket, value)
bucket value
1 1 14
2 2 12
3 3 9
4 4 20
5 5 7

然后,要求将桶中的值增加到 3(仅在允许的情况下增加)。有多种方法可以在这些存储桶上分配总共 3 个(仅随着允许的整数而增加)。

R 中是否有一个函数可以给出 5 个桶中总计 3 的所有可能分布?

更具体地说,类似于:

  distr1 distr2 distr3 distr4 distr5 distr6 ....
1 3 2 2 2 2 1 ....
2 0 1 0 0 0 2 ....
3 0 0 1 0 0 0 ....
4 0 0 0 1 0 0 ....
5 0 0 0 0 1 0 ....

我研究了 combn()expand.grid(),但那些似乎不是合适的函数......

最佳答案

这是一种可能性,即 expand.grid ,但可能不是最优雅的:

n_buckets <- 5
increase <- 3

foo <- do.call(
expand.grid,
replicate(increase, seq_len(n_buckets), simplify = FALSE)
)

res <- apply(foo, 1, function(x) {
sapply(seq_len(n_buckets), function(y) sum(y == x))
})


# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
# [1,] 3 2 2 2 2 2 1 1 1 1 2
# [2,] 0 1 0 0 0 1 2 1 1 1 0
# [3,] 0 0 1 0 0 0 0 1 0 0 1
# [4,] 0 0 0 1 0 0 0 0 1 0 0
# [5,] 0 0 0 0 1 0 0 0 0 1 0
# [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
# [1,] 1 1 1 1 2 1 1 1 1
# [2,] 1 0 0 0 0 1 0 0 0
# [3,] 1 2 1 1 0 0 1 0 0
# [4,] 0 0 1 0 1 1 1 2 1
# [5,] 0 0 0 1 0 0 0 0 1
#
# ...

注意:刚刚注意到我的答案中有冗余,因为我区分了 a在桶里1b在桶里2 ,和b在桶里1a在桶里2 。您仍然可以获得所有可能性...

编辑:删除重复项:

res[, !duplicated(res, MARGIN = 2)]

# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
# [1,] 3 2 2 2 2 1 1 1 1 1 1
# [2,] 0 1 0 0 0 2 1 1 1 0 0
# [3,] 0 0 1 0 0 0 1 0 0 2 1
# [4,] 0 0 0 1 0 0 0 1 0 0 1
# [5,] 0 0 0 0 1 0 0 0 1 0 0
# [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21]
# [1,] 1 1 1 1 0 0 0 0 0 0
# [2,] 0 0 0 0 3 2 2 2 1 1
# [3,] 1 0 0 0 0 1 0 0 2 1
# [4,] 0 2 1 0 0 0 1 0 0 1
# [5,] 1 0 1 2 0 0 0 1 0 0
# [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31]
# [1,] 0 0 0 0 0 0 0 0 0 0
# [2,] 1 1 1 1 0 0 0 0 0 0
# [3,] 1 0 0 0 3 2 2 1 1 1
# [4,] 0 2 1 0 0 1 0 2 1 0
# [5,] 1 0 1 2 0 0 1 0 1 2
# [,32] [,33] [,34] [,35]
# [1,] 0 0 0 0
# [2,] 0 0 0 0
# [3,] 0 0 0 0
# [4,] 3 2 1 0
# [5,] 0 1 2 3

关于r - 金额(仅限整数)在不同桶中的分布组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com