Combinatorial perumutations in a time series using R -
imagine time series experiment each of 3 time points (a, b, c) replicated 3 times:
a1, a2, a3, b1, b2, b3, c1, c2, c3 we concatenate data (generating time series of 3 cycles: abc,abc,abc) in possible permutations (using different time-point replicate each time). here example few realizations:
a1, b1, c1, a1, b1, c2, a1, b1, c3 a1, b2, c1, a1, b2, c2, a1, b2, c3 a1, b3, c1, a1, b3, c2, a1, b3, c3 could kindly suggest r script carry task? in advance, eran
using expand grid:
expand.grid(a = c("a1","a2","a3"), b = c("b1","b2","b3"), c = c("c1","c2","c3")) returns
b c 1 a1 b1 c1 2 a2 b1 c1 3 a3 b1 c1 ... 23 a2 b2 c3 24 a3 b2 c3 25 a1 b3 c3 26 a2 b3 c3 27 a3 b3 c3 edit: based on comments below, there more subtle trick problem.
i'm there more efficient way this, can't seem think of way beyond testing permutations:
library(gtools) library(data.table) dt <- data.table(expand.grid(a = c(1,2,3), b = c(1,2,3), c = c(1,2,3))) perm <- data.frame(permutations(nrow(dt),3,1:nrow(dt))) perm data frame possible permutations of rows.
we can create list, each element being combination:
mylist <- apply(perm,1,function(x,y){y[as.numeric(x)]},dt) we can test see list elements have every column 3 unique values
mylist[as.logical(lapply(mylist,function(x){all(lapply(x,function(y){length(unique(y))}) == 3)}))] this doozy of formula, job. returns list of 3x3 data frames meet conditions above.
edit 2: nvm, simpler:
library(data.table) library(gtools) dt <- data.table(permutations(n = 3, r = 3, v = 1:3)) perm <- data.frame(permutations(nrow(dt),3,1:nrow(dt), repeats.allowed = t)) mylist <- apply(perm,1,function(x,y){y[as.numeric(x)]},dt) mylist <- lapply(mylist,t) mylist <- lapply(mylist,`colnames<-`,c("a","b","c"))
Comments
Post a Comment