Generate data where cell counts are random, but row sums always the same

r

Solution

You are sampling from a multinomial distribution,

edit

to allow for prespecified expected cell counts

- The multinomial distribution can be considered each cell as Poisson distribution (with expected cell count), conditional on the sum.

EDIT 2

- allow for any number of rows / expected cell counts

- pass `expected` as the expected cell counts

note that `rmultinom` returns a matrix where each column is a multinomial sample, hence my use of `t` to create a single row matrix

replicates <- 10
expected <- data.frame(X1  = c(100,90,30),X2 = c(75,28,120))
##    X1  X2
## 1 100  75
## 2  90  28
## 3  30 120
data_samples <- lapply(seq(replicates), function(i, expected){
   # create a list of expected cell counts (list element = row of expected)
  .list <- lapply(apply(expected,1,list),unlist)
   # sample from these expected cell counts and recombine into a data.frame
   as.data.frame(do.call(rbind,lapply(.list, function(.x) t(rmultinom(n = 1, prob = .x,  size = sum(.x) )))))
   }, expected = expected)

This creates a list of `data.frames` with the appropriate properties

data_samples[[1]]
##    X1  X2
## 1 104  71
## 2  84  34
## 3  19 131


data_samples[[5]]
##   X1  X2
## 1 88  87
## 2 92  26
## 3 27 123

Problem

I'm in a situation where I need to create a bunch of fake datasets where the sum of two variables is the same as in my real data, but the counts for each variable are random. Here's the setup: ``` >df X.1 X.2 1 145 30 2 55 73 ``` The first row sums to 175, and the second to 128. What I'm looking for is a way to generate a data frame (or a bunch of data frames) like this: ``` >df.2 X.1 X.2 1 100 75 2 90 38 ``` In df.2, the cell counts have changed, but the rows still sum to the same table. The actual data has hundreds of rows, but only two variables if that helps. I've tried to figure out how to do this with `sample()` but haven't had any luck. Any suggestions? Thanks!

Original source