【问题标题】:All the possible outcomes所有可能的结果
【发布时间】:2016-02-25 15:25:54
【问题描述】:

我的数据框是这样的

gen<-c("A","B","C")
prob<-c("0.95","0.82","0.78")
mw<-c("10","20","50")
df<-data.frame(gen,prob,mw)

 gen prob mw
1   A 0.95 10
2   B 0.82 20
3   C 0.78 50

现在我想要 (A,B,C), (A,B),(A,C),(B,C),(A),(B),(C) 的所有可能结果,(NONE),例如 (A,B,C)=0.95*0.82*0.78= 0.60762 的概率。

trials <- data.frame(matrix(nrow=0,ncol=length(gen)))
for(i in 1:length(gen)){
  trials.tmp <- t(combn(gen,i))
  trials <- rbind(trials,cbind(trials.tmp, matrix(nrow=nrow(trials.tmp),      
  ncol=length(gen)-i ) ))
  }
 trials

V1   V2   V3
1  A <NA> <NA>
2  B <NA> <NA>
3  C <NA> <NA>
4  A    B <NA>
5  A    C <NA>
6  B    C <NA>
7  A    B   C 

但我仍然缺少组合 (NA,NA,NA)。如何制作具有所有结果和概率的新数据框。

【问题讨论】:

  • 查看combnprod 函数,以及lapply 循环。
  • 还是不知道怎么用。

标签: r


【解决方案1】:

你可以试试zx8754提到的combn,例如

a=0.95
b=0.82
c=0.78
x <- c(a,b,c)
df <- rbind(t(combn(x, 3)), cbind(t(combn(x, 2)), NA), cbind(t(combn(x, 1)), NA, NA))
apply(df, 1, function(x) prod(x[!is.na(x)]))
[1] 0.60762 0.77900 0.74100 0.63960 0.95000 0.82000 0.78000

【讨论】:

  • combinat 是干什么用的?该代码看起来像baseR。
  • combinat 用于元素的排列和组合
  • @Mot4 避免提出新问题。这不是一开始的要求。
猜你喜欢
  • 2016-03-02
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 2022-10-08
  • 2016-04-07
  • 1970-01-01
相关资源
最近更新 更多