我正在使用R编程语言。
假设我设置了以下内容:
。
我想找出(确切的解决办法):
所有可以由这5个对象组成的组合,combinations,,,
目前,我不知道如何做到这一点--我试图通过模拟“大量组合”来做到这一点,并希望我能够充分了解每种组合,从而推断出正确的概率:
library(dplyr)
results <- list()
for (i in 1:100) {
iteration = i
sample_i = sample(c("A", "B", "C", "D", "E"), size =5, replace = T, prob= c( 0.2, 0.3, 0.1, 0.3, 0.1))
my_data_i = data.frame(iteration, sample_i )
results[[i]] <- my_data_i
}
results_df <- data.frame(do.call(rbind.data.frame, results))但这看起来是解决这个问题的一个非常复杂的方法。最后,我会寻找这样的东西:
0.07
,有人能告诉我怎么做吗?
谢谢!
发布于 2022-03-07 05:15:12
每个排列的总概率是每个选定元素的概率的乘积。
library(RcppAlgos)
# Probabilities
probs <- setNames(c(0.2, 0.3, 0.1, 0.3, 0.1), LETTERS[1:5])
# Generate permutations
perms <- permuteGeneral(names(probs), repetition = TRUE)
# Collapse permutations
perm_res <- do.call(paste, c(asplit(perms, 2), sep = ""))
# Replace with probability values and coerce to numeric
perms[] <- probs[perms]
class(perms) <- "numeric"
# Calculate products
res <- data.frame(perm_res, prob = exp(rowSums(log(perms))))
head(res)
perm_res prob
1 AAAAA 0.00032
2 AAAAB 0.00048
3 AAAAC 0.00016
4 AAAAD 0.00048
5 AAAAE 0.00016
6 AAABA 0.00048
# Check total sums to 1
sum(res$prob)
[1] 1发布于 2022-03-07 04:26:50
编辑:此解决方案适用于该示例,但由于有更多有效数字的可能性,该解决方案很快会耗尽内存。
probabilities.
expand.grid相对应的对象标签向量,以生成结果中唯一行的所有可能长度-5 combinations.
的结果==概率中每个组合的可能的combinations.
objs <- c(
rep("A", 2),
rep("B", 3),
"C",
rep("D", 3),
"E"
)
combos <- expand.grid(
p1 = objs,
p2 = objs,
p3 = objs,
p4 = objs,
p5 = objs
)
combos <- paste0(
combos$p1,
combos$p2,
combos$p3,
combos$p4,
combos$p5
)
n_combos <- length(combos)
combos_unique <- unique(combos)
# number of combinations
length(combos_unique)
# 3125
# probability of each combination
setNames(
sapply(combos_unique, \(x) sum(combos == x) / n_combos),
combos_unique
)
# AAAAA BAAAA CAAAA DAAAA EAAAA ABAAA BBAAA CBAAA DBAAA EBAAA
# 0.00032 0.00048 0.00016 0.00048 0.00016 0.00048 0.00072 0.00024 0.00072 0.00024
# ACAAA BCAAA CCAAA DCAAA ECAAA ADAAA BDAAA CDAAA DDAAA EDAAA
# 0.00016 0.00024 0.00008 0.00024 0.00008 0.00048 0.00072 0.00024 0.00072 0.00024
...这个解决方案的问题是,行数不仅会随着更多的对象或更长的组合长度迅速扩展,而且还会随着具有更多有效数字的概率而迅速扩展。我只需要3“B来模拟.3的概率,但是.325的概率需要325。
https://stackoverflow.com/questions/71375997
复制相似问题