如何生成具有预测概率的随机数据集?

时间:2019-07-03 09:18:07

标签: r simulation prediction categorical-data

我正在努力生成具有预测的多项式逻辑回归概率的随机数据集。

让我们举个例子。我将使用nnet包进行多项逻辑回归。我还将使用wine包中的rattle.data数据集。

library("nnet")
library("rattle.data")
data(wine)
multinom.fit<-multinom(Type~Alcohol+Color,data=wine)
summary(multinom.fit)

Call:
multinom(formula = Type ~ Alcohol + Color - 1, data = wine)

Coefficients:
     Alcohol      Color
2  0.6258035 -1.9480658
3 -0.3457799  0.6944604

Std. Errors:
     Alcohol     Color
2 0.10203198 0.3204171
3 0.07042968 0.1479679

Residual Deviance: 222.5608 
AIC: 230.5608 

fit<-fitted(multinom.fit)
head(fit)

          1            2          3
1 0.6705935 0.0836177621 0.24578870
2 0.5050334 0.3847919037 0.11017466
3 0.6232029 0.0367975986 0.33999948
4 0.3895445 0.0007888818 0.60966664
5 0.4797392 0.4212542898 0.09900655
6 0.5510792 0.0077589278 0.44116190

因此,fit数据集是178 * 3数据帧。我想使用预测的概率生成100个随机数据集。例如,fit数据集中的第一个样本具有大约0.67的概率为'1',而0.08到'2',0.24到'3'。每个样本都是独立招募(收集?)的。

有执行的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试:

rand.list <- lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ]))
rand.df   <- data.frame(matrix(unlist(rand.list), ncol = nrow(fit)))

它将为您提供一个data.frame,其中包含100个观察值和178列,其中fit中每行的采样概率不同。

答案 1 :(得分:0)

对不起我说错话了。

例如,当我执行代码时,结果就是这样。

head(lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ])))
[[1]]
  [1] 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1
 [61] 1 1 1 1 1 1 1 1 1 1 1 1 1 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 1 1 3 1 1 1 1 1 1 1 1 1
 [61] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 3 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

但是,还有另一种方法可以在data.frame中表达它吗?当我执行data.frame函数时,结果是这样的。

head(data.frame(lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ]))))

*尽管执行head函数,但数据太长。我复制了最后两行。

  c.3L..1L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..
1                                                              3
2                                                              1
3                                                              3
4                                                              3
5                                                              3
  c.3L..1L..1L..1L..3L..3L..3L..1L..1L..1L..3L..1L..1L..3L..1L..
1                                                              3
2                                                              1
3                                                              1
4                                                              1
5                                                              3
 [ reached 'max' / getOption("max.print") -- omitted 1 rows ]

我想这样表达数据。

   1 2 3 4 5 .... (ommited)
1 1 1 3 1 1
2 1 1 3 1 1
3 1 3 3 1 1
4 1 3 1 1 3
5 1 1 3 1 1
... (omited)

因此,data.frame是178 * 100。样本数为178,随机生成试验数为100。