Generate two categorical variables with a certain association? Say, I wish to simulate two categorical variables who are associated with each other like in the table:
prop.table(table(mtcars$gear, mtcars$vs),2)

 vs
gear          0          1
   3 0.66666667 0.21428571
   4 0.11111111 0.71428571
   5 0.22222222 0.07142857


# I can generate two new variables which have the same probabilities as the original variables:

gearSim <- sample(x=0:2, size=1000, replace=TRUE, prob = table(mtcars$gear)   )

vsSim <- sample(x=0:1, size=1000, replace=TRUE, prob = table( mtcars$vs)   )


# But they are not (off course) associated with each other:

prop.table(table(gearSim, vsSim),2)

       vsSim
gearSim         0         1
      0 0.4766355 0.4365591
      1 0.3495327 0.3956989
      2 0.1738318 0.1677419

How do I get them to associate with each other, like in the table?
(mtcars is in the base dataset)
 A: You can simulate the first variable independently i.e. based on the marginal distribution provided by
table(mtcars$gear)

as you have done.
However, the second variable should then be simulated conditioned on the value of the first i.e. based on 
table(mtcars$vs[which(mtcars$gear==gearSim[i])])

, which uses only the subset of vs values for the correct gear value.
Here is some (very inelegant) example code, which simulates the vs variables conditional on gear=3,4,5 respectively and then chooses the correct result for each gear result.
gearSim <- sample(x=3:5, size=1000, replace=TRUE, prob = table(mtcars$gear))

## conditional probabilities
vsSim3 <- sample(x=0:1, size=1000, replace=TRUE, prob = table(mtcars$vs[which(mtcars$gear==3)]))
vsSim4 <- sample(x=0:1, size=1000, replace=TRUE, prob = table(mtcars$vs[which(mtcars$gear==4)]))
vsSim5 <- sample(x=0:1, size=1000, replace=TRUE, prob = table(mtcars$vs[which(mtcars$gear==5)]))
vsSimCond <- cbind(vsSim3, vsSim4, vsSim5) ## nice matrix for convenience

## select the right conditional probability depending on the value of gearSim
vsSim <- c()
for (i in 1:length(gearSim)) vsSim <- c(vsSim, vsSimCond[i, gearSim[i]-2])

## check result
prop.table(table(gearSim, vsSim),2)
        vsSim
  gearSim         0         1
        3 0.6606822 0.1602709
        4 0.1005386 0.7652370
        5 0.2387792 0.0744921

prop.table(table(mtcars$gear, mtcars$vs),2)
                   0          1
        3 0.66666667 0.21428571
        4 0.11111111 0.71428571
        5 0.22222222 0.07142857

