2016-08-02 25 views
1

我有一個數據集,包含8年的季度數據。如果我從理論上可以從理論上構建「新」年的年份中隨機選擇每個季度。例如:新年= Q1(2009),Q2(2012),Q3(2010),Q4(2015)。四分數據的所有排列

我遇到的問題是我想構建一個包含所有這些排列的數據集。 8年和4個季度,會給我4^8 = 65536「新」年。這是最好的一個嵌套循環處理,還是那裏的功能可以更好地工作?

+0

你在說什麼不是排列(在數學意義上)。閱讀該標籤或http://mathworld.wolfram.com/Permutation.html的信息 – Frank

+1

@Frank:你確實是對的。我撤回了我的評論。 – aichao

回答

1

我們可以使用expand.grid創造一切可能的組合的矩陣:

nrow(do.call('expand.grid', replicate(8, 1:4, simplify=FALSE))) 
[1] 65536 
0

您可能要稍等一下,看看是否有人給你一少「janky」的答案,但這個例子需要時間系列,每年都會有所有排列並且沒有重複的季度,並且將舊年和季度信息作爲列返回這些新的年份值。

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 

那麼要做的就是

1,以時間序列

2的所有可能的組合,刪除所有重複所以每個由一年沒有同季的它。

# 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 

這是一個相當內存密集的答案。如果有人可以跳過「制定所有可能的組合」的步驟,那麼這將是一個重大的改進。

+0

感謝您的回覆。我正在處理一個相當大的數據集,所以內存使用情況可能會成爲問題,但這給了我一個開始的好地方。 –

+0

@PaulGreeley如果你的數據是八年價值這應該是好的 –

0

我想你想在4個季度的8年多的組合,這樣的組合數爲8^4 = 4096:

> x <- years <- 2008:2015 
> length(x) 
[1] 8 
> comb <- expand.grid(x, x, x, x) 
> head(comb) 
    Var1 Var2 Var3 Var4 
1 2008 2008 2008 2008 
2 2009 2008 2008 2008 
3 2010 2008 2008 2008 
4 2011 2008 2008 2008 
5 2012 2008 2008 2008 
6 2013 2008 2008 2008 
> tail(comb) 
    Var1 Var2 Var3 Var4 
4091 2010 2015 2015 2015 
4092 2011 2015 2015 2015 
4093 2012 2015 2015 2015 
4094 2013 2015 2015 2015 
4095 2014 2015 2015 2015 
4096 2015 2015 2015 2015 
> nrow(comb) 
[1] 4096 

每一行都是一年VAR1,VAR2,VAR3,VAR4是4個季度。

+0

不,我認爲他們想每年有四分之一,而不是每季度一年。這就是爲什麼他們有比4096更大的數字。 – Frank