Sie möchten vielleicht ein bisschen warten, um zu sehen, ob jemand Ihnen eine weniger ‚janky‘ gibt Antwort, aber dieses Beispiel nimmt eine Zeit Reihe, nimmt alle Permutationen mit nicht wiederholten Vierteln innerhalb jedes Jahres, und gibt diese Neujahrswerte mit den alten Jahres- und Quartendaten als Spalten zurück.
set.seed(1234)
# Make some fake data
q_dat <- data.frame(year = c(rep(2011,4),
rep(2012,4),
rep(2013,4)),
quarters = rep(c("Q1","Q2","Q3","Q4"),3),
x = rnorm(12))
q_dat
year quarters x
1 2011 Q1 -1.2070657
2 2011 Q2 0.2774292
3 2011 Q3 1.0844412
4 2011 Q4 -2.3456977
5 2012 Q1 0.4291247
6 2012 Q2 0.5060559
7 2012 Q3 -0.5747400
8 2012 Q4 -0.5466319
9 2013 Q1 -0.5644520
10 2013 Q2 -0.8900378
11 2013 Q3 -0.4771927
12 2013 Q4 -0.9983864
Also, was tun wird, ist
1 alle möglichen Kombinationen der Zeitreihe
2 Entfernen Sie alle Duplikate so jeweils aus Jahr nicht das gleiche Quartal in er hat .
# Expand out all possible combinations of our three years
q_perms <- expand.grid(q1 = 1:nrow(q_dat), q2 = 1:nrow(q_dat) ,
q3 = 1:nrow(q_dat), q4 = 1:nrow(q_dat))
# remove any duplicate combinations
# EX: So we don't get c(2011Q1,2011Q1,2011Q1,2011Q1) as a year
q_perms <- q_perms[apply(q_perms,1,function(x) !any(duplicated(x))),]
# Transpose the grid, remake it as a data frame, and lapply over it
l_rand_dat <- lapply(data.frame(t(q_perms)),function(x) q_dat[x,])
# returns one unique year per list
l_rand_dat[[30]]
year quarters x
5 2012 Q1 0.4291247
6 2012 Q2 0.5060559
2 2011 Q2 0.2774292
1 2011 Q1 -1.2070657
# bind all of those together
rand_bind <- do.call(rbind,l_rand_dat)
head(rand_bind)
year quarters x
X172.4 2011 Q4 -2.3456977
X172.3 2011 Q3 1.0844412
X172.2 2011 Q2 0.2774292
X172.1 2011 Q1 -1.2070657
X173.5 2012 Q1 0.4291247
X173.3 2011 Q3 1.0844412
Dies ist eine ziemlich speicherintensive Antwort. Wenn jemand den Schritt "Mach alle möglichen Kombinationen" überspringen kann, dann wäre das eine deutliche Verbesserung.
Worüber Sie sprechen, sind keine Permutationen (im mathematischen Sinne). Lesen Sie die Info für dieses Tag oder http://mathworld.wolfram.com/Permutation.html – Frank
@Frank: Sie sind tatsächlich richtig. Ich ziehe meinen Kommentar zurück. – aichao