permutation - Enumeration of distinct events in R -
i searching general approach enumerate sequence associated following problem , deposit results in 3 dimensional matrix in r.
i think there must combinatorial solution have been unable find one. hopefully, detailed below sufficiently characterize problem. welcomed.
given there n periods , c distinct areas in occurrence of event e must occur once in each area, enumeration of possible sequences?
for example, if there 3 time periods {1,2,3} , 2 areas {a,b}, manually enumerating solutions gives:
period 1 2 3 area b b b sol 1 e e - - - - ; ie event occurs in both areas @ time 1, nothing happens @ time 2 , 3 sol 2 - - e e - - ; event occurs in both areas @ time 2 etc sol 3 - - - - e e sol 4 e - - e - - sol 5 e - - - - e sol 6 - e e - - - sol 7 - e - - e - sol 8 - - e - - e sol 9 - - - e e -
regardless of number of areas , number of time steps, know number of solutions n^c. case 3 ways event occur in 'a' times 3 ways event occur in 'b', 3 x 3 = 9 distinct sequences. said, wish implement generalized solution number of periods , number of areas , store result in matrix indexed [time][area][sequence]. thanks!
many thanks. believe following working correctly.
# solution: numperiods <- 4 numevents <- 2 numseqs <- numperiods^numevents gridparam <- rep(list(seq(numperiods)),numevents) g <- as.matrix(expand.grid(gridparam)) print(g) m <- t(apply(g, 1, function(z) { x <- rep(0, numperiods*numevents) (i in 1:numseqs) { x[numevents * z[i] - (numevents-i)] <- 1 } x })) print(m) result <- array(m,c(numseqs,numevents,numperiods)) colnames(result) <- outer("event",1:numevents, paste) rownames(result) <- outer("seq", 1:numseqs, paste) # time period third dim print(result)