admin管理员组

文章数量:1313001

I would like to create a matrix of 1000 rows and 91 columns filled with integers generated by the Dirichlet Multinomial distribution.

What I have achieved so far is fine for creating only one matrix (1 row with 91 columns):

library(extraDistr)
mypar <- c(0.1,0.1,0.2,0.3,0.1,0.2)

mysim <- rdirmnom(91, size=1, mypar)

#changing 1 to item number
mysim[,2] <- ifelse(mysim[,2]==1,2,0)
mysim[,3] <- ifelse(mysim[,3]==1,3,0)
mysim[,4] <- ifelse(mysim[,4]==1,4,0)
mysim[,5] <- ifelse(mysim[,5]==1,5,0)
mysim[,6] <- ifelse(mysim[,6]==1,6,0)

tokeep <- which(mysim>0)
mychoice.sim <- mysim[tokeep]
rep.y <- t(matrix(mychoice.sim))

I would like to create a matrix of 1000 rows and 91 columns filled with integers generated by the Dirichlet Multinomial distribution.

What I have achieved so far is fine for creating only one matrix (1 row with 91 columns):

library(extraDistr)
mypar <- c(0.1,0.1,0.2,0.3,0.1,0.2)

mysim <- rdirmnom(91, size=1, mypar)

#changing 1 to item number
mysim[,2] <- ifelse(mysim[,2]==1,2,0)
mysim[,3] <- ifelse(mysim[,3]==1,3,0)
mysim[,4] <- ifelse(mysim[,4]==1,4,0)
mysim[,5] <- ifelse(mysim[,5]==1,5,0)
mysim[,6] <- ifelse(mysim[,6]==1,6,0)

tokeep <- which(mysim>0)
mychoice.sim <- mysim[tokeep]
rep.y <- t(matrix(mychoice.sim))
Share Improve this question edited Feb 1 at 16:19 Ben Bolker 227k26 gold badges399 silver badges492 bronze badges asked Feb 1 at 9:44 stefanostefano 4151 gold badge8 silver badges15 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

There are probably lots of ways to do this. Here's one:

mypar<-c(0.1,0.1,0.2,0.3,0.1,0.2)
sampfun <- function() apply(extraDistr::rdirmnom(91, size=1, mypar)==1, MARGIN=1, which)
M <- t(replicate(1000, sampfun()))

From Wikipedia:

[The Dirichlet-multinomial distribution] reduces to the categorical distribution as a special case when n = 1.

A simpler approach would be to use sample:

`dim<-`(sample(length(mypar), 91e3, 1, mypar), c(1e3, 91))

本文标签: rSimulating from Dirichlet Multinomial distributionStack Overflow